我尝试在角度视图中实施确认密码验证。写新

app.js中的指令



并在确认密码文本框中添加compare-to

<div class="form-group">
        <label class="control-label col-sm-2" for="pwd">Password:</label>
        <div class="col-sm-10">
            <input type="password"
                   class="form-control"
                   placeholder="Enter password"
                   ng-model="Password"
                   ng-minlength="5">

            <span class="validationMessage" ng-show="frm.password.$dirty && frm.password.$error.required">Required!</span>
            <span class="validationMessage" ng-show="frm.password.$dirty && frm.password.$error.minlength">Min length 5!</span>
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-sm-2" for="pwd">Confirm Password:</label>
        <div class="col-sm-10">
            <input type="password"
                   class="form-control"
                   ng-model="ConfirmPassword"
                   required
                   compare-to="Password"
                   placeholder="Enter Confirm password">

            <span class="validationMessage" ng-show="frm.ConfirmPassword.$error">Required!</span>
        </div>
    </div>


但是确认密码没有显示任何验证。并显示错误消息:无法在chrome中设置未定义的属性“ compareTo”。

最佳答案

大部分都在工作。您在那里只有很少的逻辑缺陷。

首先,使用<label for="x">要求模板中包含id="x"存在的元素。那里没什么大不了的,但是当您检查form有效性时,您应该引用表单字段,而不是基础模型。

因此,您应该输入frm.<ng-model-var>.$error而不是frm.<form-field-name>.$error

您需要为输入添加名称,并再次检查表单验证逻辑。这对于您的password应该可以正常工作。

<!-- added required, input name, changed validation logic -->
<input type="password"
       name="password"
       class="form-control"
       placeholder="Enter password"
       ng-model="Password"
       required
       ng-minlength="5" />
<span class="validationMessage"
      ng-show="frm.password.$error.required">
  Required!
</span>
<span class="validationMessage"
      ng-show="frm.password.$dirty && frm.password.$error.minlength">
  Min length 5!
</span>


这是您的confirm password

<!-- added input name, changed validation logic -->
<input type="password"
       name="confirmpassword"
       class="form-control"
       placeholder="Enter Confirm password"
       ng-model="ConfirmPassword"
       required
       compare-to="Password" />
<span class="validationMessage"
      ng-show="frm.password.$valid && frm.confirmpassword.$invalid">
  Passwords do not match!
</span>

关于javascript - 确认密码自定义指令在Angular中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30341077/

10-12 03:42