Reputation: 365
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
Reputation: 490617
There are a few issues...
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./
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.{1}
quantifier is implicit, and the [0-9]
character class can be substituted with \d
.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