Javascript表单验证,if语句太多了?

时间:2013-01-13 00:16:19

标签: javascript html forms validation

我有一个包含五个元素的表单,firstNamelastNameusernamepasswordpasswordConfirmation

var errors = [];
var errorsText = [];


function generateError(messageText, elementIdentifier) {
var messageText = messageText;
var elementIdentifier = elementIdentifier;
errors.push(elementIdentifier);
errorsText.push(messageText);
return false;
}



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

var firstName = firstName;
//alert("First Name = \'" + firstName + "\'");
var lastName = lastName;
//alert("Last Name = \'" + lastName + "\'");
var username = username;
//alert("Username = \'" + username + "\'");
var password = password;
//alert("Password = \'" + password + "\'");
var passwordConfirmation = passwordConfirmation;
//alert("Password Confirmation = \'" + passwordConfirmation + "\'");

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

    generateError("You must provide a First Name", "firstName");
} 

if ( ( lastName == null ) || ( lastName == "" ) ) {
    //lastname hasn't been filled out
    generateError("You must provide a Last Name", "lastName");
}

if ( ( username == null ) || ( username == "" ) ) {
    //username hasn't been filled out
    generateError("You must enter a Username", "username");
}

if ( ( password == null ) || ( password == "" ) ) {
    //password hasn't been filled out
    generateError("You haven\'t entered a password", "password");
}

if ( ( passwordConfirmation == null ) || ( passwordConfirmation == "" ) ) {
    //passwordconfirmation hasn't been filled out
    generateError("You haven\'t confirmed your password", "passwordConfirmation");
}

validatePassword(password, passwordConfirmation);

}

有没有更好的方法来处理所有if statements

4 个答案:

答案 0 :(得分:4)

考虑创建字段名称和错误消息的映射:

var errorMessages = {
  firstName:"You must provide a First Name",
  lastName: "You must provide a Last Name",
  username: "You must enter a Username",
  password: "You haven't entered a password",
  passwordConfirmation: "You haven\'t confirmed your password"
};

也许是一个小辅助功能,可以有条件地抛出错误:

var assertIsFilled = function(name, value) {
  if(!value) {
    generateError(errorMessages[name], name);
  }
});

这将很好地清理您的验证功能:

function validateRegistrationForm(firstName, lastName, username, password, passwordConfirmation) {
  formReset();
  assertIsFilled("firstName", firstName);
  assertIsFilled("lastName", lastName);
  assertIsFilled("username", username);
  assertIsFilled("password", password);
  assertIsFilled("passwordConfirmation", passwordConfirmation);

  validatePassword(password, passwordConfirmation);
}

答案 1 :(得分:1)

这看起来像你可以使用Logical OR短路

function validateRegistrationForm(firstName, lastName, username, password, passwordConfirmation) {
    formReset();
    firstName || generateError("You must provide a First Name", "firstName");
    lastName || generateError("You must provide a Last Name", "lastName");
    username || generateError("You must enter a Username", "username");
    password || generateError("You haven\'t entered a password", "password");
    passwordConfirmation || generateError("You haven\'t confirmed your password", "passwordConfirmation");
    validatePassword(password, passwordConfirmation);
}

答案 2 :(得分:0)

您可以检查该值是否真实,而不是同时检查nullempty string

if (firstName) { 
 // value is truthy 
}

或者您可以使用以下内容,

if (!firstName) {
 // value is non-truthy
 generateError("You must provide a First Name", "firstName");
}

答案 3 :(得分:0)

你能做这样的事吗? :

jQuery(":input").bind("blur change",function(){
     if(jQuery(this).val()===null || jQuery(this).val()===""){
     generateError();
    }
})

此外,您可以过滤掉不需要以这种方式验证的输入。

Raw JS版本:

var inputs = document.getElementsByTagName('input');

for (var i=0, len=inputs.length; i<len; i++){
    if (inputs[i].type == 'text'){      
        inputs[i].onclick = function(){ 
              if(this.value===null || this.value===""){
                generateError();
              }       

        }
//same for onBlur
    }
}