I know there are a dozen questions at least on this. I am trying to have a simple validation of input for street address using Regex whereby I check for at least two spaces in the input entry. The reason? for the most part us addresses are at least 3 parts, street number, street name, type (lane, drive, ave , st ,etc)
I want to alert the user if the entry doesn't match at least that, if it has more than three spaces, meaning it has more names in the address, that's fine but the minimum not being met necessitates an alert. My latest effort is below, and is not working.
var addregex = new RegExp("^\d{1,6}\040([A-Z]{1}[a-z]{1,}\040[A-Z]{1}[a-z]{1,})$|^\d{1,6}\040([A-Z]{1}[a-z]{1,}\040[A-Z]{1}[a-z]{1,}\040[A-Z]{1}[a-z]{1,})$|^\d{1,6}\040([A-Z]{1}[a-z]{1,}\040[A-Z]{1}[a-z]{1,}\040[A-Z]{1}[a-z]{1,}\040[A-Z]{1}[a-z]{1,})$"); if (addregex.test($(this).val())) { alert('is valid'); address.addClass('isvalid'); address.css("border", "1px solid lightgray"); } else { address.css("border", "2px solid red"); alert("Are you sure this is a valid street address?"); address.focus(); } 6 7 Answers
A simple test is all you need: /^\s*\S+(?:\s+\S+){2}/
\w+(\s\w+){2,}
Description:
\w+=> Alphanumeric, one or more repititions\s=> Whitespace(\s\w+)=> A numbered capture group [\s\w+]{2,}=> at least 2 repititions
I could not get the other guys to work for some reason but this one validates all street addresses I have ever come up with...
var value = '12136 Test This Road';
var streetAddRegEx = new RegExp('/\d{1,}(\s{1}\w{1,})(\s{1}?\w{1,})+)/g');
console.log(streetAddRegEx.test(value));Basically I made it so it was any set of words more then one proceeding a set of numbers...
3You've got some viable suggestion here. I would however like to offer you a regex that I think does what you asked for:
\d+\s+\w+\s+\w+or, if it's a warning only, you could even add testing of "types" you indicated, like:
\d+\s+\w+\s+(?:st(?:\.|reet)?|ave(?:\.|nue)?|lane|dr(?:\.|ive)?)allowing for abbreviated version with or without full stop. (Add road, court, etc. at will)
Check it out at regex101.
Hope this helps,
Regards
EDIT: Remember to add flag for case insensitive. ;)
Improved version based on ClasG's answer.
/\d+(\s+\w+){1,}\s+(?:st(?:\.|reet)?|dr(?:\.|ive)?|pl(?:\.|ace)?|ave(?:\.|nue)?|rd|road|lane|drive|way|court|plaza|square|run|parkway|point|pike|square|driveway|trace|park|terrace|blvd)/ 2 ^(?!\s*$)^((?!([p|P][-. ]?[o|O].?[- ]?|post office )[b|B]([ox|OX]))(?!(\`|\~|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\+|\=|\[|\{|\]|\}|\||\\|\'|\<|\,|\.|\>|\?|\"|\;|\:)).)*$ ^(?:[A-Za-z]+[ -]?)+[A-Za-z]$
Street only. Letters, single dash/space repeated but not ending with dash/space