简体   繁体   中英

JavaScript regex to validate an address

I would like to validate residence address in the JavaScript using regex, but I dont know much about the regex, what I have tried is to build my own regex ( /^[a-zA-Z\\s](\\d)?$/ ) but it doesn't seem to work properly.

What I want to achieve is to allow letters, spaces and at least one digit (thats required) and also there should be a possibility to insert the slash / but it shouldnt be required.

Could anyone help me with that?

I'll get you started, but you'll find yourself becoming more specific as you get accustomed to regular expressions. First, let's examine your regex:

/^[a-zA-Z\s](\d)?$/

The essential thing to note here is that this regex will only match, at most, a two-character string! The character class, [ ... ] , matches a single character: in your case, letters and whitespace. You need to combine this with what's called a quantifier , eg * meaning "zero or more", + meaning "one or more", and ? meaning "zero or one". You've used a quantifier elsewhere, (\\d)? , where you're saying "zero or one" digit character. But what you really want looks more like this:

/^[a-zA-Z\s\d\/]+$/

Here, we're saying "one or more" letters, whitespace, digits, or slashes (note that the forward slash must be escaped using a backslash).

Finally, you say want to require "at least one" digit. This can be achieved with a more advanced construct in regular expressions, called "lookaround assertions." You want this:

/^(?=.*\d)[a-zA-Z\s\d\/]+$/

That, in particular, is a positive lookahead assertion , which you can research yourself. An alternate way of doing this, without lookahead assertions, would be:

/^[a-zA-Z\s\d\/]*\d[a-zA-Z\s\d\/]*$/

This is obviously more complicated, but when you're able to understand this, you know you're well on your way to understanding regular expressions. Good luck!

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