首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用javascript验证表单的正确方法(简单)

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

Stack Overflow用户
提问于 2013-01-13 02:28:11
回答 2查看 375关注 0票数 0

我有一个包含五个字段的表单:first namelast nameusernamepasswordpasswordConfirmation

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

到目前为止,我有这样的想法:

代码语言:javascript
运行
复制
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可以做到这一点,但我不确定最有效的方法。

目前我已经创建了这两个函数:

代码语言:javascript
运行
复制
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()函数,该函数将所有错误存储在一个数组中,然后逐个循环它们,向用户显示错误的内容。

EN

Stack Overflow用户

发布于 2013-01-15 08:44:25

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

另外,让我们回顾一下您的validateRegistrationForm函数。按照现在的方式,我猜它是由onsubmit触发的,但为什么不利用JavaScript的敏捷性,为用户提供每个字段的即时反馈呢?我将把它改为validateRegistrationElement,并将其命名为onchange。我们只需要传入一个参数,就是被计算的文本框。这样我们就可以使用"this“了。因此,每个文本框看起来如下所示:

代码语言:javascript
运行
复制
 <input type="text" id="firstname" onchange="validateRegistrationElement(this)" />

另外,在每个文本框旁边放一个反馈框,去掉那些烦人的提示弹出窗口。我们甚至可以用CSS类名"error“和"success”设置反馈框的样式,并将它们分别设置为红色或绿色。

代码语言:javascript
运行
复制
 <div id="firstnameFeedback"></div>

...and等等。

CSS:

代码语言:javascript
运行
复制
 .error {background-color: pink; border: 1px dashed red; color: white} 
 .success {border: 1px dashed green;}

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

代码语言:javascript
运行
复制
 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“。

代码语言:javascript
运行
复制
 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,并由上面的函数调用。

代码语言:javascript
运行
复制
 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
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14296564

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档