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

javascript - Prevent users from entering a value greater than 2 digits in an input field - Stack Overflow

programmeradmin0浏览0评论

I have a HTML form field to get the month from the user.

<input type="text" placeholder="MM" size="2" name="month">

I need the field to accept only 2 digits. I tried Form validation, but it allows the user to enter more than 2 digits and then display the validation message. I don't need any validation messages for the field, but the user should be restricted to enter only 2 digits max. Is there a way we can do this using jquery?

I have a HTML form field to get the month from the user.

<input type="text" placeholder="MM" size="2" name="month">

I need the field to accept only 2 digits. I tried Form validation, but it allows the user to enter more than 2 digits and then display the validation message. I don't need any validation messages for the field, but the user should be restricted to enter only 2 digits max. Is there a way we can do this using jquery?

Share asked Nov 25, 2016 at 18:01 StuborgStuborg 1212 silver badges15 bronze badges 1
  • I'd suggest enforcing a maximum of 12, rather than a maximum input length of two characters if you're wanting a numeric representation of the month. – David Thomas Commented Nov 25, 2016 at 18:16
Add a ment  | 

3 Answers 3

Reset to default 4

<input type="text" placeholder="MM" size="2" name="month" maxlength="2>

The maxlength attribute;

<input type="text" placeholder="MM" size="2" maxlength="2" name="month">

It limits the amount of text you can enter by straight up not allowing you to type more.

EDIT: added snippet

The easiest is using the type='number' attribute and setting max='12':

<input type='number' max='12' min='1'>

SNIPPET

input {
  width: 4ex;
  padding: 0 1px;
}
input:last-of-type {
  width: 6.5ex;
}
<fieldset>
  <legend>Enter Date</legend>
  <label>Month:</label>
  <input type='number' max='12' min='1'>

  <label>Day:</label>
  <input type='number' max='31' min='1'>

  <label>Year:</label>
  <input type='number' max='3000' min='2016'>

</fieldset>

This should help you out, whenever the user presses the key down it will check the lenght and then trim the extra chars if there are any:

$("input").keydown(function() {
    var value = $(this).val();
    if(value.length > 2) {
        value = value.substring(0, 2);
        $(this).val(value);
    }
});
发布评论

评论列表(0)

  1. 暂无评论