使用javascript验证表单的正确方法(简单)

时间:2013-01-12 18:28:11

标签: javascript validation

我的表格有五个字段; first namelast nameusernamepasswordpasswordConfirmation

我首先想说的是我不想要最复杂的方法,这是一个非常简单的网站,永远不会上线,它纯粹是为了演示目的,我不担心错误捕获有害的用户输入感。

到目前为止,我有这个:

function validateRegistrationForm(firstName, lastName, username, password, passwordConfirmation) {
alert("validate form function has been called");
//alert("function has been called");

//---


var firstName = firstName;
//alert(firstName);
var lastName = lastName;
//alert(lastName);
var username = username;
//alert(username);
var password = password;
//alert(password);
var passwordConfirmation = passwordConfirmation;
//alert(passwordConfirmation);

//---

//**The code that I have sectioned off here, I am unsure whether I need it or not, could someone please explain to me why I would do this, and not just reference the parameters in the function directly?**

// Check here if all the fields in the registeration form have been filled.

if ( firstname == null || firstname == "" ) {
    //firstname hasn't been filled out
}

if ( lastName == null || lastName == "" ) {
    //lastname hasn't been filled out
}

if ( username == null || username == "" ) {
    //username hasn't been filled out
}

if ( password == null || password == "" ) {
    //password hasn't been filled out
}

if ( passwordConfirmation == null || passwordConfirmation == "" ) {
    //passwordconfirmation hasn't been filled out
}
}

我想有办法检查每个字段是否已填写(我认为我在这里),如果没有,则生成一个通知,例如有问题的输入元素周围的红色边框和/或者包含有关如何解决问题的说明的消息。我知道这可以用css完成,但我不确定最有效的方法。

目前我已经创建了这两个功能:

function generateError(messageText, elementIdentifier) {
alert("error generator called");    
//var element = document.getElementById(elementID);
//var error = document.createTextNode(message);
//element.innerHTML = message;
alert("Element: " + elementIdentifier + ", Reason: " + messageText);
}

function validatePassword(password, passwordConfirmation) {
alert("password check called");
if (password == passwordConfirmation) {
    if (password.length < 8) {
        //password too short
        //alert("password\'s match but they are too short");

        return false;
    } else {
        //passwords match and the right length
        //alert("password\'s match and they are 8 characters or longer");
        return true;
    }
} else {
    //the two do not match
    //alert("they don\'t match")
    generateError("Passwords don\'t match", "password");
    return false;
}
}

validatePassword()函数将密码和密码确认作为两个参数,我认为这已经有效,我想要的是将生成的错误传递给generateError()函数,该函数将它们全部存储起来在一个数组中,然后逐个循环显示给用户错误。

2 个答案:

答案 0 :(得分:1)

定义复杂。我认为你的代码已经太复杂了。赠品是重复。每当你看到重复时,问问自己是否有办法将所有重复组合成一个循环。结果是代码更少,但通常代码也更友好。例如,如果要添加电话号码,则必须再添加四行代码以及另一个参数,这将破坏函数的向后兼容性,除非您添加更多代码以允许未定义的电话号码。您可能会说“我绝对不会再添加任何字段,因此这不是问题。”我不知道有多少次我说自己和我最终不得不吃掉我的话并对我的功能进行手术。此外,它只是更好的工程。

另外,让我们重新访问您的validateRegistrationForm函数。你现在拥有它的方式,我的猜测是它是由onsubmit触发的,但是为什么不通过给每个字段的用户提供即时反馈来利用JavaScript的快捷性?我要将它更改为validateRegistrationElement,它将被调用onchange。我们只传入一个参数,即正在评估的文本框。这样我们就可以使用“这个”了。所以每个文本框看起来都像:

 <input type="text" id="firstname" onchange="validateRegistrationElement(this)" />

此外,在每个文本框旁边,让我们在每个文本框旁边放置一个反馈框,摆脱那些恼人的警报弹出窗口。我们甚至可以使用CSS类名“错误”和“成功”来设置我们的反馈框,并分别将它们设置为红色或绿色。

 <div id="firstnameFeedback"></div>

......等等。

CSS:

 .error {background-color: pink; border: 1px dashed red; color: white} 
 .success {border: 1px dashed green;}

不要使用每个表单元素的详细信息加载我们的函数,而是将指令分成一种配置变量,一个对象数组。数组的每个成员都代表一个表单元素,因此在您的情况下,将有四个数组成员。这些对象包含函数在报告错误时需要知道的所有内容。我的建议是让每个对象包含表单元素的id,标签,要求(与自己的反馈消息配对的正则表达式数组是理想的,但让字符串长度保持简单),以及特殊条件用于密码匹配。

 var myFields =
  [
   {
    "id": "firstname",
    "label": "first name",
    "minLength": 1 //in other words, the field is required
   },
  {
    "id": "lastname",
    "label": "last name", 
    "minLength": 1
   }, 
  {
    "id": "password1",
    "label": "first password", 
    "minLength": 6,
    "maxLength": 8,
    "mustMatch": "password2"
   },
  {
    "id": "password2",
    "label": "second password", 
    "minLength": 6,
    "maxLength": 8,
    "mustMatch": "password1"
   }, 
  ]

这太复杂了吗?我不这么认为。现在我们有一个我们的验证器功能可以达到的一系列legos。我们可以轻松地添加或减少元素。如果我们想要的话,我们甚至可以为以后添加功能,它不会破坏功能(就像密码maxlength,我已经遗漏了函数)。我会给你看。这是新的验证器功能。请记住,只要用户更改字段中的值,就会调用此方法。该函数将知道哪一个,因为我们在html中使用了“this”。

 function validateRegistrationElement(field) {
  var message = ""; //declare an empty string literal for the message
  for (i=0;i<myFields.length; i++){ //loop through each array element until we find the object
   if(myFields[i].id == field.id){ //once we've found the config object
    if(myFields[i].minLength > field.value.length){ //if the field is shorter than what's allowed
     message += myFields[i].label + " must be longer than " + myFields[i].minLength;
    }
    if (typeof(myFields[i].mustMatch) != 'undefined'){ //if the field must match another...
     if(field.value != document.getElementById(myFields[i].mustMatch)){ //...does it match
      message += myFields[id].label +" must match "+myFields[id].mustMatch;
     }
    }
   document.getElementById(field.id + "Feedback").innerText = message;
   if (message.length > 0) {setClass(field.id, "error")} //if there an error message, highlight red
   else{setClass(field.id, "success")}//otherwise, highlight green
   }
  }
 }

请注意,这也会处理密码,因此您不需要额外的功能。

此函数管理CSS并由上述函数调用。

 function setClass(id, className) {
    document.getElementById(id).className = "";
    document.getElementById(id).className = className;
    document.getElementById(id+"Feedback").className = "";
    document.getElementById(id+"Feedback").className = className; 
 }

答案 1 :(得分:0)

尝试很棒jQuery Validation plugin

您将需要更多标记(请参阅演示和文档),只需$("#yourForm").validate();