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

使用javascript验证表单的正确方法(简单),javascript,validation,Javascript,Validation,我有一个表单,它有五个字段名字,姓氏,用户名,密码和密码确认 首先我想说的是,我不想要最复杂的方法,这是一个非常简单的网站,永远不会上线,它纯粹是为了演示的目的,我不担心错误捕获的有害用户输入的意义 到目前为止,我有: function validateRegistrationForm(firstName, lastName, username, password, passwordConfirmation) { alert("validate form function has been ca

我有一个表单,它有五个字段<代码>名字,
姓氏
用户名
密码
密码确认

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

到目前为止,我有:

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;
}
}
函数生成器错误(messageText,elementIdentifier){
警报(“调用错误生成器”);
//var element=document.getElementById(elementID);
//var error=document.createTextNode(消息);
//element.innerHTML=消息;
警报(“元素:+elementIdentifier+”,原因:+messageText);
}
函数validatePassword(密码、密码确认){
警报(“调用密码检查”);
如果(密码==密码确认){
如果(密码长度<8){
//密码太短
//警报(“密码匹配,但太短”);
返回false;
}否则{
//密码匹配且长度正确
//警报(“密码匹配,长度为8个字符或更长”);
返回true;
}
}否则{
//这两个不匹配
//警报(“它们不匹配”)
generateError(“密码不匹配”,“密码”);
返回false;
}
}

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

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

另外,让我们再次访问validateRegistrationForm函数。现在,我猜它是由onsubmit触发的,但是为什么不利用JavaScript的快速性,在每个字段上给用户即时反馈呢?我将把它改为validateRegistrationElement,它将被称为onchange。我们只需要传入一个参数,即正在计算的文本框。这样我们就可以使用“this”。因此,每个文本框的外观如下所示:

 <input type="text" id="firstname" onchange="validateRegistrationElement(this)" />
与其用每个表单元素的细节来加载函数,不如将指令分离成一种配置变量,一个对象数组。数组的每个成员将代表一个表单元素,因此在您的示例中,数组将有四个成员。这些对象包含函数报告错误所需的所有信息。我的建议是让每个对象都包含表单元素的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"
   }, 
  ]
这太复杂了吗?我不这么认为。现在我们有了一桶乐高积木,我们的验证器功能可以进入其中。我们可以很容易地增加或减少元素。如果需要的话,我们甚至可以为以后添加一些特性,这样就不会破坏函数(比如密码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
   }
  }
 }
试试看


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

我固定了一个
和一个缺少的
但我必须插入一些虚拟空格字符以达到6个字符的编辑要求。我必须按照说明更改函数
setClass
,因为函数
document.getElementById(id).removeClass()
document.getElementById(id).addClass()
不起作用(可能是jQuery?),Chromium报告的错误是
类型错误:“undefined”不是函数
。Firefox不支持方法
。innerText
,最好使用
。innerHTML
 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"
   }, 
  ]
 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
   }
  }
 }
 function setClass(id, className) {
    document.getElementById(id).className = "";
    document.getElementById(id).className = className;
    document.getElementById(id+"Feedback").className = "";
    document.getElementById(id+"Feedback").className = className; 
 }