JQuery zip check not working

I am trying to check a zip field using jQuery, but it does not work.

Here is my code:

if (postcod.val().match ('~^([1-9]{1}[0-9]{3}\s[AZ]{2})$~')){ }else{ postcod.addClass("needsfilled"); postcod.val(postcoderror); } 

Here is the html:

 PostCode<br /><input id="postcod" type="text" value="" name="postcod" /> 

Could you help plz

+4
source share
1 answer

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})$/)){ ... } 
+7
source

All Articles