简体   繁体   中英

password confirmation in angular 2

I am trying to check whether the two passwords are equal. I am not getting any error message when there are not but i am not getting the error message "Password must match" .

Below is my DOM:

<div class="form-group" [ngClass]="{'has-error': formName.get('password').touched && 
                formName.get('password').hasError('invalidPassword')}">
    <label class="control-label">Password</label>
    <input type="text" class="form-control" formControlName="password" name="password" required />
</div>

<div class="form-group" [ngClass]="{'has-error': formName.get('confirmpassword').touched 
        && formName.get('confirmpassword').hasError('mismatchedPasswords')}">
    <label class="control-label">confirm password</label>
    <input type="text" class="form-control" formControlName="confirmpassword" name="confirmpassword" required />
    <span class="help-block" *ngIf="formName.get('confirmpassword').touched 
            && formName.get('confirmpassword').hasError('mismatchedPasswords')">
            Password must match
        </span>
</div>

My Component class on how i am building my form:

   this.formName = this.fb.group({
        name: ["", [Validators.required]],            
        password: ["",[Validators.required, ValidationHelper.passwordValidator]],
        confirmpassword: ["",Validators.required],
        info: this.fb.group({
            acc: ["",[Validators.required, ValidationHelper.creditCardValidator]]
        })
   },{ validator: ValidationHelper.matchPass})

And my password matching function:

static matchPass = (control: AbstractControl) : {[key: string]: boolean} => {    
    let password = control.get('password');
    let confirmPassword = control.get('confirmpassword');
    return password.value === confirmPassword.value ? null : { 'mismatchedPasswords': true };        
}  

The function is getting called, i am also getting the return value... but why is my confirm password input control not showing error or activitating its span tag.

The issue is with these lines in your template:

formName.get('confirmpassword').hasError('mismatchedPasswords')

You're applying the validator to the group formName , but checking for the error on the confirmpassword formControl.

Try using this in the two places where you check for mismatchedPasswords in your template.

formName.hasError('mismatchedPasswords')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM