I'm trying to validate text field using JavaScript. It should allow (az, white space between words, and AZ).
I tried this but it doesn't work:
function formValidator(){
var name = document.getElementById('name');
if(isAlphabet(name, "Please enter only letters for your name")){
return true;
}
return false;
}
function isAlphabet(elem, helperMsg){
var alphaExp = /^[a-zA-Z.,\b]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
I think your regex should look like this:
/^[a-z]+(\s+[a-z]+)*$/i
This allows AZ (case-insensitive because of /i
), followed by any amount of white-space characters and AZ again. The last part may be repeated or doesn't need to be present at all.
单词之间只能有一个空格:
/^[a-z]+( [a-z]+)*$/i.test(str);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.