Mary
Mary

Reputation: 365

jQuery postcode validation does not work

I am trying to validate postcode field using jQuery but it does not work.

Here is my code:

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

Here is html:

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

Could you help plz

Upvotes: 4

Views: 1885

Answers (1)

alex
alex

Reputation: 490617

There are a few issues...

  • Regexs are not quoted in JavaScript, unless you need to create a RegExp object via its constructor. In this circumstance, you don't. I only use them if I need to concatenate an outside string. While you can pass a string to match() and it will be implicitly converted, it's not recommended over passing a RegExp literal.
  • You need to use / as the delimiters in a regex literal. When using the RegExp, you don't pass any delimiters. So ~ are never correct. Perhaps you are thinking PHP.
  • Whilst not necessary, some of your regex could be improved. The {1} quantifier is implicit, and the [0-9] character class can be substituted with \d.
  • Instead of having an empty block and an else, just negate the condition with the bang operator (!).

Here is how I might use it...

if ( ! postcod.val().match(/^([1-9]\d{3}\s[A-Z]{2})$/)){
   ...
}

Upvotes: 7

Related Questions