我一直在尝试使用JavaScript创建验证,其中输入应该只是字母和空格。每次输入数字时,它仍会传递数字输入。请查看下面的代码并帮助我解决代码中的错误。
function validateForm()
{
var x=document.forms["form1"]["fname"].value;
if (x==null || x=="") {
alert("Enter Firstname");
return false;
}
else {
if (!x.value.match(/^[a-zA-Z ]+$/) && x.value != "") {
alert("You entered an invalid Firstname");
return false;
}
}
答案 0 :(得分:0)
你的regexp应该代表那样的东西
/^[a-zA-Z\s]+$/
空间有特殊字符("") - \ s 此外,!x.value.match中存在错误。您已经拥有x的值。
因此,您的完整功能应如下所示:
function validateForm() {
// get the edit and get its value
var edit = document.forms["form1"]["fname"].value;
// if there are no value in the edit, or
// there is only spaces and the string then return false
if (edit.trim() == "") {
alert("Enter your first name");
return;
}
// else if there is something, then let's check it
// this pattern allows any letter characters (both BIG and small)
// and spaces
// pay attention that the block inside this "if" will execute
// if no matches will found (e.x if there will digits in the input string)
// so it will works as we excepted
if (!edit.match(/^[a-zA-Z\s]+$/g)) {
alert("Enter correct first name!");
return false;
}
// everything seems to be ok, return true
// alert('ok');
return true;
}