Reputation: 537
I want to validate a text field (first name) using javascript. such that it should only contain text. NO special characters and No numbers.and since it is just the first name it should only contain one word. (no spaces)
Allowed:
Not Allowed
I tried this but its not working.
if( !validateName($fname))
{
alert("name invalid");
}
function validateName($name) {
var nameReg = /^A-Za-z*/;
if( !nameReg.test( $name ) ) {
return false;
} else {
return true;
}
}
EDIT: I tried
var nameReg = /^[A-Za-z]*/;
but it still doesn't show the alert box when I enter john123 or 123john.
Upvotes: 1
Views: 9653
Reputation: 25081
Use a character class:
var nameReg = /^[A-Za-z]*/;
Without the containing []
(making it a character class), you're specifying a literal A-Za-z
.
UPDATE:
Add a $
to the end of the Regex.
var nameReg = /^[A-Za-z]*$/;
Otherwise, john123
returns valid as the Regex is matching john
and can ignore the 123
portion of the string.
Working demo: http://jsfiddle.net/GNVck/
Upvotes: 1
Reputation: 191749
nameReg
needs to be /^[a-z]+$/i
(or some varient). The ^
matches the start of the string and $
matches the end. This is "one or more a-z characters from the start to the end of the string, case-insensitive." You can change +
to *
, but then the string could be empty.
http://jsfiddle.net/ExplosionPIlls/pwYV3/1/
Upvotes: 2