Search code examples
angularjsng-patternng-messages

ng-pattern passwords match


hi am creating a register form and I want to check using angular if the passwords that the user has entered match. All my validations work (required, min & max length) but i always get the error that the passwords do not match.

My code is as follows

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

I am thinking that the problem might be in the ng-pattern="/^{{password_1}}$/" but i don't know how i can debug that so i can see the value of the ng-parent.

Any help will be much appreciated! Andreas.


Solution

  • You want to use ng-pattern="{{newCustomerInfo.password_1}}". password_1 is not defined, and per the doc:

    If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it in ^ and $ characters. For instance, "abc" will be converted to new RegExp('^abc$') a.k.a /^abc$/.