javascript - Check input for 4 numbers and 2 letters with jQuery - Stack Overflow

I have a text <input> withmaxlength="6" but I want to check if the first 4 characters

I have a text <input> with maxlength="6" but I want to check if the first 4 characters are numbers and the last 2 are letters.

I have this code:

$("input[id='post']").keyup(function count() {
   //what goes here?
});

but I really don't know how to go on further.

I have a text <input> with maxlength="6" but I want to check if the first 4 characters are numbers and the last 2 are letters.

I have this code:

$("input[id='post']").keyup(function count() {
   //what goes here?
});

but I really don't know how to go on further.

Share Improve this question edited Oct 7, 2013 at 16:03 CSᵠ 10.2k9 gold badges43 silver badges64 bronze badges asked Oct 7, 2013 at 10:06 FvOFvO 723 silver badges12 bronze badges 2
  • try keypress instaed of keyup – bhb Commented Oct 7, 2013 at 10:12
  • 1 Define "numbers" and do you expect only latin letters?. – meze Commented Oct 7, 2013 at 10:12
Add a ment  | 

4 Answers 4

Reset to default 4

You can use RegEx to do this

$("input[id='post']").keyup(function count() {
    var input = this.value;
    var regex = new RegExp(/^[0-9]{4}[a-z]{2}$/i);
    console.log(regex.test(input));
});

[0-9]{4} - Checks for four digits between 0-9.

[a-z]{2} - Checks for two letters between a-z. The i flag at the end makes the check case-insensitive.

You can use regular expressions:

https://developer.mozilla/en/docs/Web/JavaScript/Guide/Regular_Expressions

Something like:

$("input[id='post']").keyup(function count() {
    var valid = /^\d{4}[a-zA-Z]{2}$/.test(this.value);
});

so that valid will be true if the input matches your condition, and false otherwise.

This will log Valid to console if it matches the required pattern:

$('#post').keyup(function() {
    if (/^\d{4}[a-zA-Z]{2}$/.test(this.value)) {
         console.log("Valid");
    }
});

You can use a regular expression like this ^[0-9]{4}[a-z]{2}$ and make a key up/down function to use it

See this link from to test the usage

Demo Testing and regex explained

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745378329a4625105.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信