Iti Tyagi
Iti Tyagi

Reputation: 3661

Regular Expression for Alphabetical text with some exceptions

I am looking to for Regular Expression for a text field which accepts alphabets, also dots(.), brackets, -, & like

A.B.C
ABC (new),
A & A co.
A-abc.

I have my regular expression:

/^[A-z.&() ]+$/

code:

var regex = /^[a-z][a-z.()&-]+$/;
var sel = document.getElementById("TextBoxID").value;
if (sel != "-- Select --") {
if (!regex.test(sel.toString())) {
alert("Please use a proper name.");
}
} return false;

I want the string to mandatory start with alphabet. But seems like this is not working when I add - into the same, may be the syntax is wrong.

Upvotes: 1

Views: 200

Answers (1)

Andrew Cheong
Andrew Cheong

Reputation: 30273

First, note that [A-z] is not the same as [A-Za-z], which is probably what you meant. If you look at an ASCII table, you can see that the range from A to z includes several special characters that you may not intend to include.

Second, since the dash - denotes a range in a character class (as above), it must be included last (or first, but more commonly last) in order to be interpreted as a literal dash.

So, what you really want is this:

/^[A-Za-z.()&-]+$/

And to assert that it starts with an alphabet:

/^[A-Za-z][A-Za-z.()&-]*$/
  ^^^^^^^^             ^

(Notice I've changed the + quantifer to a * quantifier.)

Finally, as @ExplosionPills had done, you can simplify the expression by making it case-insensitive:

/^[a-z][a-z.()&-]*$/i

Upvotes: 3

Related Questions