I have a form which allows only for numbers to be entered in the text box, or an alert appears:
<form name="formName" action="" method="post" OnSubmit="return chkSubmit();">
Input Number
<input type="text" name="txtNumber" value="">
<input type="submit" name="btnSubmit" value="Submit">
</form>
with the following javascript:
<script>
function chkSubmit()
{
if(isNaN(document.formName.txtNumber.value))
{
alert('Please input numbers only.');
return false;
}
}</script>
How do I allow for only 4 characters to be entered? No alert, just prevent the user from typing more than 4 characters.
inputelements support amaxlengthattribute, e.g.:…which is then enforced by the user agent (browser). You can also enforce it in your
chkSubmitif you want a belt-and-braces approach, by checking the length of thevalueproperty, but it’s been around forever and I doubt you’ll find a user agent that doesn’t handle it.RobG’s point (in a comment on the question) is well-taken, as well: Restricting users prior to form submission tends to be irritating for them. It may or may not be appropriate for your use-case, but at least consider not limiting them (but perhaps giving some visual feedback using the
keypressevent), and only validating length on submit, the way Stack Overflow does on comments.