0

I have two factories (because it is more readable) and one controller. I do not know if it is possible, but I want to sent the result of the two factories in one variable.

code

vm.result = [];
vm.validate = validate;
function validate(password1, password2) {
    vm.result = comparePasswordFactory.compare(password1, password2) + validNumberFactory.valid(password1);
    return vm.result;
}

compare returns:

return {
     color: 'green',
     text: 'Passwords match',
     validate1: 'true'
};

valid returns:

return {
    text: 'Number should be between 12 and 45',
    validate2: 'false'
};

I do not think what I wrote is correct. But, is this possible and/or is it a good option ?

1
  • What is the result from your factories? It looks like bools, but the "+" operator doesn't work with bools. Use "&&". Commented Jun 6, 2016 at 7:49

1 Answer 1

1

in order to validate using both functions you have to read and compare its validate1 / validate2 properties

var passwordOK = comparePasswordFactory.compare(password1, password2).validate1 === 'true';
var numberOK = validNumberFactory.valid(password1).validate2 === 'true';
vm.result = passwordOK && numberOK;

tip: better way would be to use boolean values instead of string, eg.

return {
    validate: false
}

pro way: consider using consistent api in your factories, then you could do something like:

var validators = [comparePasswordFactory, validNumberFactory];
var isValid = true;
for(var i=0;i<validators.length;i++){
    if(!validators[i].validate.call(this, password1, password2)){
        isValid = false;
        break;
    }
}
vm.result = isValid;

then you could easily add another validator (notice that all factories must implement validate method)

Sign up to request clarification or add additional context in comments.

2 Comments

Did you wanted to say validate variable ?
no, validate method (which is now compare in password factory and valid in number factory)

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.