There are a few problems ...
- Regexs are not cited in JavaScript unless you need to create a
RegExp object through your constructor. In this case, you do not. I only use them if I need to concatenate an outer string. Although you can pass the string to match() and it will be implicitly converted, it is not recommended to pass the letter RegExp . - You need to use
/ as delimiters in the regular expression literal. When using RegExp you do not pass any delimiters. Therefore ~ never true. Perhaps you are thinking about PHP. - Although not necessary, some of your regular expressions could be improved. The coefficient
{1} implicit, and the character class [0-9] can be replaced by \d . - Instead of having an empty block and
else , just cancel the condition using the bang ( ! ) Operator.
Here is how I can use it ...
if ( ! postcod.val().match(/^([1-9]\d{3}\s[AZ]{2})$/)){ ... }
source share