【问题标题】:Why don't work custom validator (Angular 5)为什么不使用自定义验证器(Angular 5)
【发布时间】:2018-03-25 23:57:39
【问题描述】:

当我需要在注册表单中检查相等的两个字段时,我遇到了这种情况。它是输入密码和重复密码。我为此任务创建了我的验证器。但是对于相等的两个字符串检查,我需要在我的验证器中获取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 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)

尽管我在ngOnInit() -this.validateMatchPasswords.bind(this) 中绑定了this,但form 对象在validateMatchPasswords 方法中不可用

为什么会出现此错误^以及如何解决此问题?谢谢!

我使用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>

【问题讨论】:

  • 你可以为你的代码创建提琴手/codepen吗?
  • @VicJordan 抱歉不明白。你对 fiddler/codepen 意味着什么?
  • 创建您的代码的executable code snippet

标签: javascript angular5 angular4-forms


【解决方案1】:

创建一个表单组并在该组上添加一个验证器。这是一个未经测试的示例,但它应该可以工作(我过去曾使用过这种方法)。

@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;
    }
}

【讨论】:

    猜你喜欢
    • 2019-02-12
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多