JavaScript Regex Zipcode validation issue - Stack Overflow

I am using the following regex for validating 5 digit zipcode. But it is not working.var zipcode_regex

I am using the following regex for validating 5 digit zipcode. But it is not working.

var zipcode_regex = /[\d]{5,5}/;
if (zipcode_regex.test($.trim($('#zipcode').val())) == false)
alert('invalid zipcode');

I am also using jQuery in the code snippet.

I am using the following regex for validating 5 digit zipcode. But it is not working.

var zipcode_regex = /[\d]{5,5}/;
if (zipcode_regex.test($.trim($('#zipcode').val())) == false)
alert('invalid zipcode');

I am also using jQuery in the code snippet.

Share Improve this question edited Nov 24, 2021 at 13:19 Nimantha 6,4836 gold badges31 silver badges76 bronze badges asked May 9, 2012 at 9:45 Pramod SivadasPramod Sivadas 8932 gold badges10 silver badges29 bronze badges 1
  • 1 But it is not working. What is happening and what do you expect to happen? Please provide some example input and output and be more precise. – Felix Kling Commented May 9, 2012 at 9:48
Add a ment  | 

2 Answers 2

Reset to default 6

Your regex also matches if there is a five-digit substring somewhere inside your string. If you want to validate "only exactly five digits, nothing else", then you need to anchor your regex:

var zipcode_regex = /^\d{5}$/;
if (zipcode_regex.test($.trim($('#zipcode').val())) == false)
    alert('invalid zipcode');

And you can get that more easily:

if (!(/^\s*\d{5}\s*$/.test($('#zipcode').val()))) {
    alert('invalid zipcode');
}

This regex just matches exactly 5 digits:

/^\d{5}$/

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

相关推荐

  • JavaScript Regex Zipcode validation issue - Stack Overflow

    I am using the following regex for validating 5 digit zipcode. But it is not working.var zipcode_regex

    17小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

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

关注微信