Limiting the Length of Input text



It is often desirable to limit the length of the text being entered in a form. Although a separate string processing can be used, the regular expression solution is more elegant in some cases, as, it can be combined with other rules that govern the text being entered. As an example the following regular expression will limit the username to a minimum of 3 characters and maximum of 15 characters and allow only lowercase letters and digits

^[a-z0-9]{3,15}$

The complete example

<html>
<body>
<script type="text/javascript">
<!--
/*
********************************************************
Javascript Regular Expression Example 25
Form validation example
********************************************************
*/
function validate( )
{
var calForm = document.getElementById('form1');
var pattern= /^[a-z0-9]{3,15}$/ ;
if (pattern.test(calForm.uname.value))
{
calForm.instruction.value = "The username is correct";
}
else {
calForm.instruction.value ="Only small case and digits min 3 and max 15";
}
}
//---->
</script>
</head>
<body>
<br> Username validation <br />
<br />
<form method="post" id="form1" name="form1">
<table>
<tbody>
<tr>
<td><b> Enter Username :</b></td> <td> <input name="uname" size="20"></td>
<td> <input name="instruction" value = "<-- enter username here" size="40"> </td>
</tr>
<tr>
<td>
<input id="button2" name="button2" value="Submit" onclick="validate()" type="button"></td>
</tr>
</tbody></table>
</form>
</body>
</html>


Try this Example online


You can try this example online at - here .



Figure 1.1 : The username validation Form



Figure 1.2 : The username validation – Correct Input



Figure 1.3 : The username validation – Incorrect Input

Of course, the actual implementation will vary and we will have more exotic displays than the one shown above. The purpose of this program is to show the use of the regular expression in form validation and in restricting the length of the input.

The length restriction can also be used to restrict the length of the textbox input in a form.