使用JavaScript进行输入验证

Input validation using JavaScript

本文关键字:输入 验证 JavaScript 使用      更新时间:2023-09-26

我一直在尝试使用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;
       }
 }

您的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;
}

示例:http://cssdeck.com/labs/lagfrayg