Javascript Regex Zipcode for validation

I use the following regular expression to validate a 5 digit zip code. But that does not work.

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

I also use jQuery in the code snippet.

Please, help..

+4
source share
2 answers

Your regular expression also matches if there is a five-digit substring in your line. If you want to check "just five digits, nothing more", you need to anchor your regular expression:

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

And you can get it easier:

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

Just use /^\d{5}$/ .

body

must be at least 30 characters; you entered 21

+1
source

Source: https://habr.com/ru/post/1411483/


All Articles