0

I have many functions written in JavaScript such as userName(), password() etc. But on submitting on the form, I have a single function return formValidator();.

I want function to call all the other functions and check whether they are returning false or not. If they all are true than it should return true, otherwise it should return false.

function userName(){
      var x=document.forms["signupform"]["firstname"].value;
            if(x=="" ||x==null){
           document.getElementById("firstname").style.border="1px solid #F50A0A";
           document.getElementById("firstname").style.boxShadow="2px 2px 5px #F50A0A";
           return false;
      }else {return true;}
}

function password(){
 var z=document.forms["signupform"]["password"].value;
      if(z=="" ||z==null){
            document.getElementById("password").style.border="1px solid #F50A0A";
           document.getElementById("password").style.boxShadow="2px 2px 5px #F50A0A";
            return false;
      }else {return true;}
}
1

3 Answers 3

6

You can call each function, using the && operator to indicate that each one must return something that evaluates to true. If any one of them returns something that evaluates to false, the entire statement will evaluate to false:

function formValidator() {
    return userName() && password() && somethingElse() && etc();
}
Sign up to request clarification or add additional context in comments.

1 Comment

What do you mean by "not working"? What happens? Any errors in the JavaScript console?
1
var validators = [userName, password, ...];
function formValidator() {
    return validators.every(function(fn){return fn();});
}

or just use the AND operator:

function formValidator() {
    return userName() && password() && ...;
}

Comments

0

It should be as simple as:

function formValidator()
{
    var username = userName();
    var password = password();

    return username && password; // or just return userName() && password();
}

2 Comments

if( condition_which_returns_boolean_true_or_false ) { return true is redundant. just return the condition evaluation.
yes it is, I just wanted you to update it to remove the redundancy. I am not one of the downvoters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.