admin管理员组

文章数量:1193816

I am new to javascript, so I apologize if this is all totally wrong, but I'm trying to validate a form right now, and I have the simple functions for testing. I want the function validateForm() to return all three of the functions checkName(), checkEmail, and checkMessage(). The way I have the validateForm() function, it only runs the checkName() function. Any ideas?

function checkName(){

    var name=document.forms["contactForm"]["Name"].value;

    if(name==null || name==""){
        $("input#name").css("border-color", "#ff0000");
        $("input#name").attr("placeholder","Your name is required");
        return false;    
    }    
    else {
        $("input#name").css("border-color", "#00a8ff");
        $("input#name").attr("placeholder","");
        return true;
    }    
}

function checkEmail(){

    var email=document.forms["contactForm"]["Email"].value;

    if(email==null || email==""){
        $("input#email").css("border-color", "#ff0000");
        $("input#email").attr("placeholder","Your email is required");
        return false;    
    }    
    else {
        $("input#email").css("border-color", "#00a8ff");
        $("input#email").attr("placeholder","");
            return true;
        }
}

function checkMessage(){

    var message=document.forms["contactForm"]["Message"].value;

    if(message==null || message==""){
        $("textarea#message").css("border-color", "#ff0000");
        $("textarea#message").attr("placeholder","Your message is required");
        return false;    
    }    
    else {
        $("textarea#message").css("border-color", "#00a8ff");
        $("textarea#message").attr("placeholder","");
        return true;
    }
}

function validateForm(){

    return checkName() && checkEmail() && checkMessage();

}

I am new to javascript, so I apologize if this is all totally wrong, but I'm trying to validate a form right now, and I have the simple functions for testing. I want the function validateForm() to return all three of the functions checkName(), checkEmail, and checkMessage(). The way I have the validateForm() function, it only runs the checkName() function. Any ideas?

function checkName(){

    var name=document.forms["contactForm"]["Name"].value;

    if(name==null || name==""){
        $("input#name").css("border-color", "#ff0000");
        $("input#name").attr("placeholder","Your name is required");
        return false;    
    }    
    else {
        $("input#name").css("border-color", "#00a8ff");
        $("input#name").attr("placeholder","");
        return true;
    }    
}

function checkEmail(){

    var email=document.forms["contactForm"]["Email"].value;

    if(email==null || email==""){
        $("input#email").css("border-color", "#ff0000");
        $("input#email").attr("placeholder","Your email is required");
        return false;    
    }    
    else {
        $("input#email").css("border-color", "#00a8ff");
        $("input#email").attr("placeholder","");
            return true;
        }
}

function checkMessage(){

    var message=document.forms["contactForm"]["Message"].value;

    if(message==null || message==""){
        $("textarea#message").css("border-color", "#ff0000");
        $("textarea#message").attr("placeholder","Your message is required");
        return false;    
    }    
    else {
        $("textarea#message").css("border-color", "#00a8ff");
        $("textarea#message").attr("placeholder","");
        return true;
    }
}

function validateForm(){

    return checkName() && checkEmail() && checkMessage();

}
Share Improve this question edited Jul 8, 2012 at 18:12 Danilo Valente 11.3k8 gold badges54 silver badges70 bronze badges asked Jul 8, 2012 at 18:10 user1510389user1510389 611 gold badge1 silver badge2 bronze badges 2
  • Your code seems to be correct. But "return multiple functions" doesn't make sense. You can return a value returned by a function. You can return AND'ed results of 3 functions. After all, you can return an array of 3 functions (but it is totally not this case). What is your problem? Why do you think your code works wrong? – Pavel Strakhov Commented Jul 8, 2012 at 18:18
  • @user1510389 As the answers all say && immedately returns false as soon as one of the operands (from left to right) is false. Dmitry's answer is best, and you should use it, but rename variables a, b, and c to something meaningful. Beware of hacks, though. It turs out that the replacing all instances of && with & in the return statement will also work for you, but the reasons why are very technical and the approach is not recommended. Understanding it, though, may give you insight into short-circuiting which is very valuable. – Ray Toal Commented Jul 8, 2012 at 18:26
Add a comment  | 

7 Answers 7

Reset to default 9

Operator && executes left operand (checkName in your case), and, if it is false, immediately returns false without executing right operand. So, you need to manually execute each of your function and only then connect them via &&.

function validateForm(){
    var a = checkName();
    var b = checkEmail();
    var c = checkMessage();
    return a && b && c;
}
 var yourdomain = {};
 yourdomain.validateFormField = function(){
 var domNameElement = document.getElementById("name");
 var domMailElement = document.getElementById("mail");
 var domMsgElement  = document.getElementById("msg");

 return {
           validateName: function (){
           /*your checkName() code goes here with a function return*/;
           `enter code here`},

           validateMail: function (){
            /*your checkEmail() code goes here with a function return*/;
           },

           validateMsg: function (){
            /*your checkMessage() code goes here with a function return*/;
           },
       };
  }

You can call it as bellow.

yourdomain.validateFormField.validateName()

or

yourdomain.validateFormField.validateMail()

or

yourdomain.validateFormField.validateMsg()

depending upon the need.

What you encounter is called short circuiting. Javascript logical operators do short circuits. That means if you have the expression test1() && test2() and the first function returns false, then the whole expression will always evaluate to false, nevertheless what the second function returns. Thus the second function is never called. If the first function returns true, the second function will be called however, since it actually influences the evaluation of the expression.

Thus, if checkName() returns false, then the other functions are not called. If it returns true, then checkEmail() will be called. If it also returns true, then checkMessages() will also be called. If any of the functions returns false however, the remaining functions will not be evaluated due to short circuiting.

The way that you have it currently tries to evaluate them in order due to short-circuit evaluation. If one of the items return false then the process ends.

The short-circuit expression x Sand y (using Sand to denote the short-circuit variety) is equivalent to the conditional expression if x then y else false; the expression x Sor y is equivalent to if x then true else y.

You want to call the functions separately to execute each check:

function validateForm(){
    var results = [];
    result[0] = checkName();
    result[1] = varcheckEmail();
    result[2] = checkMessage();
}

In my javascript project I did this.

return {
   checkName : checkName,
   checkEmail : checkEmail,
   checkMessage : checkMessage,
   validateForm : validateForm
};

If checkName() is false, then the other functions won't be executed because the result would still be false.

I did a bit different from others. Created an array, added all results of my validation methods and than compared each value (AND);

function ValidateInputs() {
    var arrValidations = new Array();

    arrValidations.push(ValidateProponentDocument());
    arrValidations.push(ValidateProponentName());
    arrValidations.push(ValidateProponentBirthdate());

    var ret = true;
    $.each(arrValidations, function (index, item) {
        ret &= item;
    });      

    return ret;
}

本文标签: javascriptReturn multiple functionsStack Overflow