使用反应形式以角度验证密码和确认密码

时间:2018-12-11 07:29:36

标签: javascript angular validation angular-reactive-forms

我在下面附加了我的代码。im在添加密码不匹配验证时遇到问题。如果我输入不匹配的密码,im不会收到验证错误

register.component.html

<div class="form-group row mt-3">
 <label class="col-md-4 col-lg-4 text-center">UserName:<span style="color:red">*</span></label>
<input kendoTextBox required type="text" class="  col-md-6 col-lg-6 form-control " placeholder="Enter Your UserName " formControlName="username"/>
  <div *ngIf="(submitted||f2.username.touched) && f2.username.invalid" class="error-msg">
 <div *ngIf="f2.username.errors.required">UserName  is required</div>
 </div> </div>
 <div class="form-group row">
<label class="col-md-4 col-lg-4 text-center">Password:<span style="color:red">*</span></label>
<input kendoTextBox type="password" required  class="  col-md-6 col-lg-6 form-control " placeholder="Enter Your passowrd " formControlName="password"/>

 <div *ngIf="(submitted||f2.password.touched) && f2.password.invalid" class="error-msg">
<div *ngIf="f2.password.errors.required">password  is required</div>
<div *ngIf="f2.password.errors.minlength">minimum of 6 characters required</div>
    </div>
</div>
<div class="form-group row">
   <label class="col-md-4 col-lg-4 text-center">ConfirmPassword:
<span style="color:red">*</span></label>
<input kendoTextBox required type="password" class="  col-md-6 col-lg-6 form-control " placeholder="Enter Your new password " formControlName="confirmpassword"/>
 <div *ngIf="(submitted||f2.confirmpassword.touched) && f2.confirmpassword.invalid" class="error-msg">
 <div *ngIf="f2.confirmpassword.errors.required"> confirm password  is required</div>  <div *ngIf="f2.confirmpassword.errors.minlength">minimum of 6 characters required
</div>
<div class="error-msg" *ngIf="f2.errors?.mismatch && (f2.controls['confirmpassword'].required || f2.controls['confirmpassword'].touched)">
                              Passwords don't match.
</div>
                          </div>
                      </div>
    enter code here

registercomponent.ts文件

在这里我使用了formBuilder.Other一切正常,仅验证不匹配项不起作用

 this.registerForm3 = this.formBuilder.group({
    username:['', Validators.required],
    password: ['', [Validators.required, Validators.minLength(6)]],
    confirmpassword:['', [Validators.required, Validators.minLength(6)]],
  },
  {validator: this.passwordMatchValidator},
  );

passwordMatchValidator(frm: FormGroup) {
eturn frm.controls['password'].value === 
frm.controls['confirmpassword'].value ? null : {'mismatch': true};
    }
 get f2() { 
    return this.registerForm3.controls; 
  }

5 个答案:

答案 0 :(得分:3)

我认为您不能将组件成员函数(方法)用于自定义验证器。我认为它必须是您的类外部的函数。

我的看起来像这样:

function emailMatcher(c: AbstractControl): { [key: string]: boolean } | null {
  const emailControl = c.get('email');
  const confirmControl = c.get('confirmEmail');

  if (emailControl.pristine || confirmControl.pristine) {
    return null;
  }

  if (emailControl.value === confirmControl.value) {
    return null;
  }
  return { 'match': true };
}

我将验证器附加到子formGroup上,如下所示:

this.customerForm = this.fb.group({
  firstName: ['', [Validators.required, Validators.minLength(3)]],
  lastName: ['', [Validators.required, Validators.maxLength(50)]],
  emailGroup: this.fb.group({
    email: ['', [Validators.required, Validators.email]],
    confirmEmail: ['', Validators.required],
  }, { validator: emailMatcher }),
  phone: ''
});

您可以将验证器放在单独的文件中,或放在组件类上方或下方的同一文件中。像这样:

function passwordMatchValidator(frm: FormGroup) {
  return frm.controls['password'].value === 
frm.controls['confirmpassword'].value ? null : {'mismatch': true};
}

然后,您将定义不带this关键字的验证器:

{validator: passwordMatchValidator},

您可以在此处找到完整的示例:https://github.com/DeborahK/Angular-ReactiveForms/tree/master/Demo-Final

答案 1 :(得分:1)

最后我找到了解决方法

export class ConfirmPasswordValidator {
    static MatchPassword(control: AbstractControl) {
       let password = control.get('password').value;

       let confirmpassword = control.get('confirmpassword').value;

        if(password != confirmpassword) {
            control.get('confirmpassword').setErrors( {ConfirmPassword: true} );
        } else {
            return null
        }
    }
}

答案 2 :(得分:0)

您可以像下面那样检查两者的表单值。

<div class="error-msg" *ngIf="registerForm3.value.password !== registerForm3.value.confirmpassword">
    Passwords don't match.
</div>

答案 3 :(得分:0)

您可以尝试此操作对我有用...

以您的形式

this.passwordForm = this.fb.group({
        newPassword: ['', [Validators.required, Validators.minLength(6)]],
        confirmNewPassword: ['', [Validators.required, Validators.minLength(6), (control => ValidationService.confirmPassword(control, this.passwordForm, 'newPassword'))]]
    });

ValidationService文件

static confirmPassword(control: FormControl, group: FormGroup, matchPassword: string) {
    if (!control.value || group.controls[matchPassword].value !== null || group.controls[matchPassword].value === control.value) {
        return null;
    }
    return { 'mismatch': true }
}

答案 4 :(得分:0)

对于 角度8 ,您可以使用这样的自定义验证。

导入所需的库

import { FormGroup, FormControl, Validators, ValidatorFn, ValidationErrors } from '@angular/forms';


const passwordErrorValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
  const password = control.get('a');
  const repeatPassword = control.get('b');
  return password.value != repeatPassword.value ? { 'passwordError': true } : null;
};

这样的初始化表单

 heroForm = new FormGroup({   
    'a': new FormControl(),
    'b': new FormControl()
  }, { validators: passwordErrorValidator });

在组件中

 <form [formGroup]="heroForm" (ngSubmit) ="createUser(heroForm.value)">
                <input id="a" name="a" class="form-control"
                required minlength="4"
                formControlName="a">
                <input id="b" name="b" class="form-control"
                required minlength="4"
                formControlName="b" >
                 <div *ngIf="heroForm.errors?.passwordError && (heroForm.touched || heroForm.dirty)" class="cross-validation-error-message alert alert-danger">
                  password mismatch
              </div>
              <input type="submit" class="btn btn-primary" value="Submit" />
            </form>