ng-pattern密码匹配

时间:2016-02-05 11:12:44

标签: angularjs ng-pattern ng-messages

您正在创建注册表单,如果用户输入的密码匹配,我想使用angular进行检查。我的所有验证工作(必需,最小和最大长度),但我总是得到密码不匹配的错误。

我的代码如下

<div class="control-group">
<label class="control-label">Password</label>
<div class="controls" ng-class="{ 'has-error': addCustomerForm.password_1.$touched && addCustomerForm.password_1.$invalid }">
    <input type="text" name="password_1" class="form-control input-lg" ng-model="newCustomerInfo.password_1" ng-minlength="4" ng-maxlength="12" required>
    <div ng-messages="addCustomerForm.password_1.$error" ng-if="addCustomerForm.password_1.$touched">
        <div ng-message="required">This field is required</div>
        <div ng-message="minlength">The password is too short.</div>
        <div ng-message="maxlength">The password is too long.</div>
    </div> 
</div>
</div>


<div class="control-group">
<label class="control-label">Password (Confirm)</label>
<div class="controls" ng-class="{ 'has-error': addCustomerForm.password_2.$touched && addCustomerForm.password_2.$invalid }">
    <input type="text" name="password_2" class="form-control input-lg" ng-model="newCustomerInfo.password_2" ng-minlength="4" ng-maxlength="12" ng-pattern="/^{{password_1}}$/" required>
    <div ng-messages="addCustomerForm.password_2.$error" ng-if="addCustomerForm.password_2.$touched">
        <div ng-message="required">This field is required</div>
        <div ng-message="minlength">The password is too short.</div>
        <div ng-message="maxlength">The password is too long.</div>
        <div ng-message="pattern">The passwords do not match.</div>
    </div> 
</div>
</div>

我认为问题可能在 ng-pattern =“/ ^ {{password_1}} $ /”但我不知道如何调试,所以我可以看到ng-parent的值。

任何帮助将不胜感激! 安德烈亚斯。

1 个答案:

答案 0 :(得分:4)

您想使用ng-pattern="{{newCustomerInfo.password_1}}"password_1未定义,并且根据文档:

  

如果表达式求值为字符串,则在将其包装成^$个字符后,它将转换为RegExp。例如,"abc"将转换为new RegExp('^abc$') a.k.a /^abc$/