在 AngularJS 中使用 $validators 管道进行密码匹配会产生意想不到的结果 [英] Password matching in AngularJS using the $validators pipeline produces unexpected results

查看:26
本文介绍了在 AngularJS 中使用 $validators 管道进行密码匹配会产生意想不到的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处查看示例.

使用 $validators 管道,我试图检查一个字段是否包含与另一个字段相同的值.

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:

  • 在 input#1 中输入一个值
  • 在 input#2 中输入相同的值
  • 两个字段现在都应该有效
  • 更改 input#1 中的值
  • input#1 应该是无效的(或 input#2 或两者都无效)

最初,我在当前模型和要等于的目标上使用 $watch 来做到这一点,因此只有两个字段中的一个需要使用该指令.但是,随着 $validators 管道的引入,此方法意外停止工作(可能是错误).

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).

无论如何,如您所见,当第二个输入更改时,相关输入的接收值是 undefined.

Anyhow, as you can see, when the second input is altered, the value is receives for the associated input is undefined.

我通过以下方式解决了这个问题:

I solved this by the following:

JSFiddle

正如 Nikos 所说,两个实例相互抵消,因此通过以下代码修复:

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).

推荐答案

一个问题是,当验证器失败(返回 false)时,底层模型值被设置为 undefined.所以:

One problem is that when a validator fails (returns false), then the underlying model value is set to undefined. So:

  1. 你在密码中输入了一些东西,比如 "aaa";这与 passwordConfirm NOT 相同,因此验证器返回 false 并且模型获得 undefined
  2. 您在 passwordConfirm 中输入了相同的值;但是从上面密码的值是undefinedundefined !== "aaa",所以passwordConfirm验证器也返回false.立>
  3. 等等...
  1. You type something in the password, say "aaa"; this is NOT the same as passwordConfirm, so the validator returns false and the model gets the undefined value
  2. You type the same value in passwordConfirm; but from above the value of the password is undefined and undefined !== "aaa", so the passwordConfirm validator returns false too.
  3. And so on...

这篇关于在 AngularJS 中使用 $validators 管道进行密码匹配会产生意想不到的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆