ng-message无法使用重新键入密码验证AngularJS

时间:2016-01-31 05:45:25

标签: javascript angularjs ng-messages

以下是我的代码,它可以正常使用密码,但不知何故,重新输入密码验证不起作用。让我知道我在这里做错了什么。

  <div class="form-group has-feedback">
    <input type="password" class="form-control" placeholder="Password" ng-model="vm.user.password" name="password" required="" ng-minlength="6" ng-maxlength="20" />
    <div class="help-block" ng-messages="userForm.password.$error" ng-if="userForm.password.$touched">
      <p ng-message="minlength, maxlength, required">Please enter a password containing 6 to 20 characters.</p>
    </div>        
  </div>
  <div class="form-group has-feedback">
    <input type="password" class="form-control" placeholder="Retype password" name="retypePassword" required="" ng-model="vm.user.retypePassword">
    <div class="help-block" ng-messages="userForm.retypePassword.$error" ng-if="userForm.retypePassword.$touched">
      <p ng-message when="vm.user.retypePassword !== vm.user.password" >Please retype your correct password.</p>
    </div>

DOCS中,他们提到我们可以使用表达式,但不知何故它不能验证。

3 个答案:

答案 0 :(得分:0)

我相信你的用法不对。 when属性用于多消息情况,它使用字符串键或键数组检查定义的错误是否存在,就像ng-message属性一样。

您可以使用指令创建自定义验证器,例如解释here

你也可以使用类似这样的ng-change函数来操作$ error对象:

<input type="password" ng-model="vm.user.retypePassword"
    ng-change="setMatchError(userForm.retypePassword,userForm.password)">

然后在您的控制器中

vm.setMatchError = function(input1, input2) {
    if (input1.$viewValue!=input2.$viewValue) {
         input1.$error.match = true;
    } else {
         delete input1.$error['match'];
    }
 }

最后,您将能够使用ng-message指令

来引用它
<p ng-message="match">Your passwords must match!</p>

<p ng-message when="match">Your passwords must match!</p>

虽然在应用程序代码中直接操作角度对象时,最后一种方法可能会不受欢迎。

有一点要注意,但是,如果输入没有通过其html5验证,模型没有更新,那么你将无法参考模型值。

最后一个选项:您可以完全依赖确认密码忽略ng-message(s)指令(因为它实际上不会给你太多)并且只使用ng-if  和ng-change和直接模型验证。

答案 1 :(得分:0)

在这种情况下,您可以使用有助于创建自己的检查的指令use-form-error,例如ng-required,ng-minlength或ng-pattern。

<form name="ExampleForm">
  <label>Password</label>
  <input ng-model="password" required />
  <br>
  <label>Confirm password</label>
  <input ng-model="confirmPassword" required use-form-error="dontMatch" use-error-expression="password && confirmPassword && password!=confirmPassword" />
  <div ng-messages="ExampleForm.$error" class="errors">
    <div ng-message="dontMatch">
      Passwords Do Not Match!
    </div>
  </div>
</form>

直播示例jsfiddle

答案 2 :(得分:0)

documentation here中所述 您需要在when属性中提供错误名称 如果你需要使用表达式,你需要把你的表达式放在消息块中,所以改变你的div块就像这样

<div class="help-block" ng-messages="multipleValueExpression">
      <p ng-message when="value1" >Please retype your correct password.</p>
</div>

或者您可以通过时间更改 来实现相同目标

<p ng-message when-exp="vm.user.retypePassword !== vm.user.password" >Please retype your correct password.</p>
祝你好运