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:
- John
- john
Not Allowed
- john kennedy.
- John kennedy.
- john123.
- 123john.
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.
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:
- John
- john
Not Allowed
- john kennedy.
- John kennedy.
- john123.
- 123john.
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.
Share Improve this question edited Jan 12, 2015 at 17:13 vsync 131k59 gold badges340 silver badges423 bronze badges asked Feb 24, 2013 at 17:26 user1910290user1910290 5374 gold badges15 silver badges28 bronze badges 2- In your EDIT you forgot $ at the end, without it everything will pass validation. – Igor Jerosimić Commented Feb 24, 2013 at 17:40
- Have you tried /[^A-Za-z]/g ? adding the global "g" makes it look at all the characters. – peterchon Commented Aug 13, 2013 at 23:48
2 Answers
Reset to default 2nameReg
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/ExplosionPIlls/pwYV3/1/
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/GNVck/
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745150581a4613850.html
评论列表(0条)