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
2 Answers
Reset to default 6Your 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
评论列表(0条)