pd93
pd93

Reputation: 1136

Validating forms with Regular Expressions (Javascript Regex)

I have an input form which needs to be validated in real time (.Keyup and .Load)

It should allow all A-z characters (Upper & lower) and the symbols "'", "-" and " " (apostrophe, dash and whitespace).

At the moment this is what I have: ([A-Za-z]-\s\')* and I'm using it like this:

var regex = /([A-Za-z]\-\s\')*/;
if (string == "") {
  turn textbox border grey (default)
} else if (!regex.test(string)) {
  turn textbox border red
} else {
  turn textbox border green
}

All it does it change the the textbox green every time (Unless it's blank - it goes grey). What's the correct expression/technique and what am I doing wrong?

Upvotes: 0

Views: 87

Answers (1)

Andrew Clark
Andrew Clark

Reputation: 208405

You need something like the following:

var regex = /^[A-Za-z\-\s']*$/;

The ^ and $ are beginning and end of string anchors, respectively. Without these the match could start or end anywhere in the string. Since * means "repeat the previous element zero or more times" you will match every string no matter the contents because the regex can successfully match zero characters.

The other issue with your current regex is that [A-Za-z]\-\s\' will try to match a letter, a dash, a single whitespace character, and an apostrophe in order (4 characters total). To match any one of those options you need to put them all inside of the character class (square brackets), or use alternation with the pipe character (|) which would look like ([A-Za-z]|-|\s|'). Alternation is more general but character classes are the preferred method for something like this.

Regarding the escaping, apostrophe has no special meaning in regular expressions so it does not need to be escaped. A dash only needs to be escaped if it is inside of a character class (if it isn't escaped it is interpreted as part of a range).

Upvotes: 3

Related Questions