I am trying to modify this script to accept , - and ' for this regex to validate addresses on a form is it written correctly?
^[a-zA-Z0-9\s\,\''\-]*$
It works but there are some redundant escapes.
You need not escape comma,single quote and hyphen. You escape only when the char has a special meaning and you want to use it literally. Inside a char class:
-
is a meta char, but not when it
appears at the start or at the end.
In your case it appears at the end so
it has lost its special meaning (of
range making).]
is a meta char which marks the
end of char class. So if you want to
make ]
part of char class you need
to escape it.So you can write your regex as:
^[a-zA-Z0-9\s,'-]*$
In the comments, Daniel Vandersluis has a really good point: Addresses can't be verified by merely a regex. The USPS has an entire division called CASS (Coding Accuracy Support System) dedicated to verifying address data. I work for SmartyStreets where we provide CASS-Certified services for people. In fact, if you're truly interested in good addresses, I'll help you personally in getting started (it's really easy with Javascript, for example. Just takes a minute or so.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With