使用javascript验证表单的正确方法(简单)
Correct method to validate a form using javascript (simple)
我有一个有五个字段的表单;first name
, last name
, username
, password
, passwordConfirmation
.
我首先想说的是,我不想要最复杂的方法,这是一个非常简单的网站,永远不会上线,这纯粹是为了演示的目的,我不担心在有害的用户输入的意义上的错误捕获。
到目前为止,我有这个:
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()
函数,该函数将它们全部存储在一个数组中,然后逐个循环显示给用户什么是错误的
定义复杂。我认为你的代码已经太复杂了。泄露的信息是存在重复。每当你看到重复的时候,问问自己是否有办法把所有的重复组合成一个循环。其结果是代码更少,但通常代码也更易于更改。例如,如果要添加一个电话号码,就必须再添加四行代码和另一个参数,这将破坏函数的向后兼容性,除非您添加更多的代码以允许未定义的电话号码。您可能会说:"我绝对不会添加任何字段,所以这不是问题。"我不知道我自己说过多少次了,最后我不得不收回我的话,对我的功能做了手术。此外,这只是更好的工程。
另外,让我们重新审视validaterregistrationform函数。您现在使用的方式,我猜它是由onsubmit触发的,但是为什么不利用JavaScript的快捷性,为用户提供每个字段的即时反馈呢?我要把它改成validaterregistrationelement它会被称为onchange。我们只会传入一个参数,即正在求值的文本框。这样我们就可以用"this"了。所以每个文本框看起来像这样:
<input type="text" id="firstname" onchange="validateRegistrationElement(this)" />
另外,让我们在每个文本框旁边放一个反馈框,去掉那些烦人的提示框。我们甚至可以用CSS类名"error"answers"success"来样式化我们的反馈框,并将它们分别设置为红色或绿色。
<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"
},
]
是不是太复杂了?我不这么想。现在我们有了一桶乐高,我们的验证器函数可以接触到它。我们可以很容易地加减元素。如果我们想的话,我们甚至可以在以后添加功能,而且它不会破坏函数(比如密码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;
}
试试jQuery验证插件。
您将需要更多的标记(参见演示和文档),只需$("#yourForm").validate();
。
- JQuery:向多个匹配结果添加换行符的最简单方法
- 简单的JavaScript方法链接
- 任何一种简单的方法都可以将带有onload的元素作为目标
- 访问对象的最简单方法'的单独财产
- 检查变量是否为字符串的简单方法
- 有没有一种简单的方法可以用Lodash映射嵌套数据
- 创建jQuery Slider的简单方法
- 你知道使用javascript游戏引擎的简单方法吗
- 简单的javascript方法问题
- 解释分号的简单方法
- 在javascript regexp中捕获多个变量的一种更简单的方法
- 有没有一种简单的方法可以将整数转换为等效文本.即:1变为1
- JavaScript:检查变量是否等于两个或多个值之一的简单方法
- JS方法显示了未定义的简单示例
- 有没有一种简单的方法可以用包含id和名称(从a到Z)的对象填充数组
- 调用影子原型方法的更简单/更好的方法
- 什么'这是使用jQuery将一些文本锚定到外部链接的最简单方法
- 实施会员系统的最简单方法是什么
- 有没有方法简单地将JSON数组值转换为javascript中的字符串
- 使用javascript验证表单的正确方法(简单)