admin管理员组文章数量:1334955
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}$/
本文标签: JavaScript Regex Zipcode validation issueStack Overflow
版权声明:本文标题:JavaScript Regex Zipcode validation issue - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742296608a2448858.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论