Home > Net >  Check all values in && comparison?
Check all values in && comparison?

Time:11-05

JavaScript is known to only check the first variable in a && comparison in case the first variable returns false. Is there a way to 'ask' JavaScript to check both variables i.e. when they are methods?

For example: Suppose you have 2 methods that validate 2 separate user inputs:

const validateEmail = value => {
    if(value.contains('@')){
        setShowEmailError(false);
        return true;
    }
    setShowEmailError(true);
    return false;
};

const validatePswd = value => {
    if(value !== ''){
        setShowPswdError(false);
        return true;
    }
    setShowPswdError(true);
    return false;
};

Then check both conditions:

if(validateEmail(email) && validatePswd(pswd)){
    //validate entire form and render errors
}

However, the above will not execute the validatePswd method if the first method validateEmail returns false.

Is there a way to check if both values are true and run both methods? Having JavaScript run both methods would be a breeze in some cases.

CodePudding user response:

You can execute them in an array and then accumulate the result with && by reduce function.

const validateEmail = value => {
    if(value.includes('@')){
        //setShowEmailError(false);
        return true;
    }
    //setShowEmailError(true);
    console.log('wrong email')
    return false;
};

const validatePswd = value => {
    if(value !== ''){
        //setShowPswdError(false);
        return true;
    }
    // setShowPswdError(true);
    console.log('wrong password');
    return false;
};
// you can execute any number of validations within the array.
const result = [validateEmail('something'), validatePswd('')].reduce((acc, f) => acc && f, true);

console.log(result)

UPDATE

Or as @lux suggested using every method.

const validateEmail = value => {
    if(value.includes('@')){
        //setShowEmailError(false);
        return true;
    }
    //setShowEmailError(true);
    console.log('wrong email')
    return false;
};

const validatePswd = value => {
    if(value !== ''){
        //setShowPswdError(false);
        return true;
    }
    // setShowPswdError(true);
    console.log('wrong password');
    return false;
};
// you can execute any number of validations within the array.
const result = [validateEmail('something'), validatePswd('')].every(r => r);

console.log(result)

CodePudding user response:

I don't know if you are looking for something like this:

const valEmail = validateEmail(email);
const valPsw = validatePswd(pswd);

if(valEmail && valPsw ){
    //validate entire form and render errors
}
  • Related