最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

validation - javascript, limit number of characters in text field - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Oct 31, 2012 at 0:26 tpg2114 15.1k6 gold badges45 silver badges58 bronze badges asked Oct 30, 2012 at 23:10 user1699085user1699085 1
  • 1 Restricting input like that is annoying for users. You only care that the field is valid when the form is submitted, whatever it contains before then is of no interest to you. – RobG Commented Oct 30, 2012 at 23:14
Add a ment  | 

2 Answers 2

Reset to default 5

input elements support a maxlength attribute, e.g.:

<input type="text" name="txtNumber" value="" maxlength="4">

...which is then enforced by the user agent (browser). You can also enforce it in your chkSubmit if you want a belt-and-braces approach, by checking the length of the value property, 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 ment 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 keypress event), and only validating length on submit, the way Stack Overflow does on ments.

Use maxlength

<form name="formName" action="" method="post" OnSubmit="return chkSubmit();"> 
    <input type="text" name="txtNumber" maxlength="4" value="" />
    <input type="submit" name="btnSubmit" value="Submit" />
</form>
发布评论

评论列表(0)

  1. 暂无评论