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

javascript - Validate jquery regex - number start with 931 - Stack Overflow

programmeradmin10浏览0评论

I need to validate number that use inputs into input box. Number must be exactly 12 characters long and start with 931.

var reg = /^931[0-9]$/;
var val = $("#sms_number").val();

if (val.length === 12 && reg.test(val)) {                    


}

Above is incorrect.

I need to validate number that use inputs into input box. Number must be exactly 12 characters long and start with 931.

var reg = /^931[0-9]$/;
var val = $("#sms_number").val();

if (val.length === 12 && reg.test(val)) {                    


}

Above is incorrect.

Share Improve this question edited May 20, 2013 at 11:53 georg 215k56 gold badges322 silver badges400 bronze badges asked May 20, 2013 at 11:49 renathyrenathy 5,37520 gold badges92 silver badges155 bronze badges 1
  • The main problem here is that [0-9] means "any digit between 0 and 9", but repeated just once. Your code would work find if you used [0-9]+ (meaning "any digit between 0 and 9, repeated 1 or more times") – h2ooooooo Commented May 20, 2013 at 11:55
Add a ment  | 

3 Answers 3

Reset to default 5
var reg = /^931\d{9}$/;
var val = $("#sms_number").val();
if (reg.test(val)) {
    // ....
}

You can do this without regex too.

var val = $("#sms_number").val();

if (val.length === 12 && val.toString().indexOf("931") == 0) {                    

}

Simple but probably not as robust as regex solutions

In a concise way the following should work:

/^931[0-9]{9}$/.test($("#sms_number").val())? console.log(true): console.log(false);

xdazz's answer is correct, but I'd suggest not to use \d if you are not trying to acmodate unicode numbers as well. If you are fine with only English numbers (I think that's the way it meant to be, as it uses 931 prefix which is indeed in English) you should use [0-9] instead of \d. Former is faster.

发布评论

评论列表(0)

  1. 暂无评论