为什么不使用自定义验证器(Angular 5)

时间:2018-03-25 23:57:40

标签: javascript angular5 angular4-forms

我遇到需要在注册表单中检查两个字段的情况。它输入密码和重复密码。我为此任务创建了验证器。但是对于相同的两个字符串检查,我需要在验证器中获取form对象:

export class RegistrationComponent implements OnInit {

  private formSubmitAttempt: boolean; 
  form: FormGroup;                   

  constructor(private fb: FormBuilder,        
              private authService: AuthService) {
  }

  ngOnInit() {
    this.form = this.fb.group({     // {5}
      username: ['', [Validators.required, Validators.minLength(5)]],
      password: ['', [Validators.required, Validators.minLength(5)]],
      dpassword: ['', [Validators.required, this.validateMatchPasswords.bind(this)]],
      email: ['', [Validators.required, Validators.email]]
    });
  }

  validateMatchPasswords(control: FormControl) {
    const err = this.form.get('password').value === this.form.get('dpassword').value;
    return {
      error: false
    };
  }

  onSubmit() {
    ...
  }
}

validateMatchPasswords - 我的验证方法,但它会生成  ERROR:

 ERROR TypeError: Cannot read property 'get' of undefined
    at RegistrationComponent.validateMatchPasswords (registration.component.ts:32)
    at eval (forms.js:759)
    at Array.map (<anonymous>)
    at _executeValidators (forms.js:759)
    at FormControl.eval [as validator] (forms.js:711)
    at FormControl.AbstractControl._runValidator (forms.js:3433)
    at FormControl.AbstractControl.updateValueAndValidity (forms.js:3387)
    at new FormControl (forms.js:3905)
    at FormBuilder.control (forms.js:7899)
    at FormBuilder._createControl (forms.js:7965)

尽管我form validateMatchPasswords this ngOnInit() this.validateMatchPasswords.bind(this) angular.material <div class="signin-content"> <mat-card> <mat-card-content> <form [formGroup]="form" (ngSubmit)="onSubmit()"> ... <mat-input-container class="full-width-input"> <input matInput type="password" placeholder="Create new password" formControlName="password" required> <mat-error *ngIf="isFieldInvalid('password')"> Please inform your password. Minimum 5 symbol. </mat-error> </mat-input-container> <mat-input-container class="full-width-input"> <input matInput type="password" placeholder="Repeat you're password" formControlName="dpassword" required> <mat-error *ngIf="isFieldInvalid('dpassword')"> Passwords do not match </mat-error> </mat-input-container> ... </form> </mat-card-content> </mat-card> </div> 401,但"key"方法无法使用"key"对象

为什么我会遇到此错误^以及如何解决此问题?谢谢!

我使用Parameter来构建我的组件:

paramater

1 个答案:

答案 0 :(得分:0)

创建表单组并在该组上添加验证程序。这是一个未经测试的例子,但它应该有用(我以前使用过这种方法)。

@Component({...})
export class MyComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = fb.group({
            email: [null, Validators.email],
            passwords: fb.group({
                password: [null, Validators.required],
                passwordConfirmation: [null, Validators.required]
            }, {validator: this.shouldMatchValidator('password', 'passwordConfirmation')
        });
    }

    shouldMatchValidator(...props: string[]) {
        return (group: FormGroup): any => shouldMatch(group, ...props);
    }

    shouldMatch(group: FormGroup, ...props: string[]): any {
        const ctrls = group.controls;
        const len = props.length;

        for (let i = 1; i < len; i++) {
            if (ctrls[props[0]]) {
                if (ctrls[props[0]].value !== ctrls[props[i]].value) {
                    return {invalid: true};
                }
            } else {
                throw new Error(`The property '${props[0]}' passed to 'shouldMatch()' was not found on the form group.`);
            }
        }

        return null;
    }
}