views:

35

answers:

1

I am having two text fields in my form. The data to be entered in the field are Name and City respectively. I want to check that the user has not entered any special symbols like !,@,#........ i.e, the only thing user should enter must be belonging to a-z,A-Z, though the user can enter Underscore(_), but no numbers, no special symbols.

I want to check this using JavaScript, how can this be achieved.

Thanks in advance.

+2  A: 

A classic problem that's usually solved with the help of regular expressions.

var myString = "London";
if (myString.match(/^[a-zA-Z_]+$/)) {
    // Success
}

If you want to allow spaces, like for New York, change the pattern to /^[a-zA-Z_\s]+$/.

Ed
Thanks for the answer, but can you explain how this works?
Logan
Be careful, what chars you disallow there. Maybe citizens of e.g. Montréal like to use your form too.
Dr.Molle
Google for regular expressions. They're used to match patterns in strings, like your city name. In my example, the match will be successful if the string only contains lowercase/uppercase letters and underscore. If there is anything else, it will fail.http://www.w3schools.com/jsref/jsref_obj_regexp.asp
Ed
And what about Saint John’s, Aix-en-Provence or Αθήνα (i.e. Athens)?
Edgar Bonet
*and*, with some cities accepting money to change their name to a website or email or something, they may even have colons, periods, or @ in their name
bemace
@Edgar Bonet: I am fine with user dropping "'" from his/her name. The cities name is optional, If he can't mention it, he can leave it.
Logan
@bemace: Thats right, but I won't allow user to have a city name with colons, @ or things of the kind. I am fine with pure names(Without spl symbols)
Logan