Scott
Scott

Reputation: 6251

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?

Upvotes: 2

Views: 11235

Answers (1)

Andrew Cheong
Andrew Cheong

Reputation: 30273

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, e.g. * 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!

Upvotes: 5

Related Questions