问题
See the example here.
Using the $validators pipeline, I am trying to check that a field contains the same value as another field.
Each input in this example is associated with the other, such that the expected result is as follows:
- Enter a value in input#1
- Enter same value in input#2
- Both fields should now be valid
- Alter the value in input#1
- input#1 should be invalid (or input#2 or both)
Initially, I did this using a $watch
on both the current model and the target to be equal to, so only one of the two fields needed to use the directive. However, with the introduction of the $validators
pipeline, this method stopped working unexpectedly (maybe a bug).
Anyhow, as you can see, when the second input is altered, the value is receives for the associated input is undefined
.
Solution
I solved this by the following:
JSFiddle
As Nikos said, the two instances were cancelling each other out, so this was fixed by the following code:
$scope.$watch('passwordWatch', function(pass) {
$control.$validate();
});
So now, when the target input changes, the current input revalidates. When the current input changes, it validates automatically (as usual).
回答1:
One problem is that when a validator fails (returns false
), then the underlying model value is set to undefined
. So:
- You type something in the password, say
"aaa"
; this is NOT the same aspasswordConfirm
, so the validator returnsfalse
and the model gets theundefined
value - You type the same value in passwordConfirm; but from above the value of the password is
undefined
andundefined !== "aaa"
, so the passwordConfirm validator returnsfalse
too. - And so on...
来源:https://stackoverflow.com/questions/24385104/password-matching-in-angularjs-using-the-validators-pipeline-produces-unexpecte