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
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}$/

本文标签: JavaScript Regex Zipcode validation issueStack Overflow