JavaScript Regex Zipcode validation issue

javascript, regex

Solution

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');
}

Problem

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.

Original source