Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Regular Expression to validate an address

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\,\''\-]*$
like image 423
Amen Avatar asked Nov 28 '22 23:11

Amen


2 Answers

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,'-]*$
like image 153
codaddict Avatar answered Dec 06 '22 04:12

codaddict


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.)

like image 42
Matt Avatar answered Dec 06 '22 04:12

Matt