Reputation: 6251
I want to validate zipcode or pincode in address fields. that's why I am trying to write regular express which is just except a-z
(upper and lower both), 0-9
numbers, round brackets (eg. ()
) and hyphen -
and space. But some rules must be followed like single white space can not be on first position, two or more white space can not be allowed.
some of invalid entries
1254588
125 255
((125)) 255
125--255
(125) (255)
125>2458
EL$ 2458
@L$ 2458
Upvotes: 0
Views: 309
Reputation: 336478
If those are all the rules that matter, it's easy:
^ # Start of string
(?! ) # First character mustn't be space
(?!.* ) # No two spaces in a row
[A-Za-z0-9 ()-]* # Match any number of these allowed characters
$ # End of string
or, for JavaScript:
/^(?! )(?!.* )[A-Za-z0-9 ()-]*$/
but I'm guessing that strings like "))))(((("
, "-------"
, "A"
or even ""
shouldn't actually be matched, but are allowed by your rules.
Upvotes: 3