简体   繁体   中英

JavaScript Regular Expression to validate an address

我正在尝试修改此脚本以接受 , - 和 ' 以便此正则表达式验证表单上的地址是否正确编写?

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

Above answered Regex gives false when your input is "House No.-780". The user can add "." to the address, therefore we have to make regex which accepts dot also. You can use this regex

/^[a-zA-Z0-9\s,.'-]{3,}$/ . 

This regex accepts minimum three character and there is no limit on max characters. Characters may include az, AZ alphabets, whitespace, comma(,), dot(.), apostrophe ('), and dash(-) symbols.

If you just want to accept any of those characters (or an empty string), then you can modify what you have currently to:

/^[a-z0-9\s,'-]*$/i

This is by no means a street address validator, however. I suggest you learn more about regular expressions from somewhere. http://www.regular-expressions.info/examples.html is a good place to start.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM