angular如何为模板驱动表单的跨字段验证编写指令

时间:2019-01-09 03:27:31

标签: angular angular7

所以我想创建一个验证者密码并确认密码(两个字段的值应该相同)。

这可以通过创建一个crosse字段验证器来实现,该验证器获取这两个formControls并比较它们的值 by following this tutorial

export function fieldMatcherValidator(field1: string, field2: string): ValidatorFn {
    return (control: AbstractControl): {[key: string]: boolean} | null  => {
    const checkControl = control.get(field1);
    const confirmControl = control.get(field2);
    if (checkControl.pristine || confirmControl.pristine) {
        return null;
    }
    //.....more code compare values
}

然后,我可以在组件中设置反应形式:

this.passwordForm = this.fb.group({
      password: new FormControl(undefined, [Validators.required]),
      confirmPassword: new FormControl(undefined, [Validators.required])
    }
    , {validator: fieldMatcherValidator('password', 'confirmPassword')}
    );

----上面的代码以反应形式完美工作

我的问题是:如何为验证程序编写指令,以便我也可以以模板驱动方式使用它。

我尝试编写如下指令,但该验证器不是假定可在formControl上使用,而应在formGroup上。以下指令无法获取formGroup及其控件,因此我无法验证formControls的值。

@Directive({
  selector: '[cmFieldMatcher]',
  providers: [
    {provide: NG_VALIDATORS, useExisting: FieldMatcherDirective, multi: true}
  ]
})
export class FieldMatcherDirective implements Validator {
  @Input() field1: string;
  @Input() field2: string;

  validator: ValidatorFn;

  constructor() {
    this.validator = fieldMatcherValidator(this.field1, this.field2);
  }

  validate(control: AbstractControl) {
    return this.validator(control);
  }
}

当我在这样的模板中使用它时,我没有运气来获取abstractControl实例...

<form #form="ngForm" cmFieldMatcher [field1]="'password2'" [field2]="'confirmPassword2'">
                <cm-form-field>
                    <cm-password-input  name="password2" ngModel #password2="ngModel" [label]="'Password'" required [strengthLevel]="passwordStrength" [messages]="passwordMessages">
                    </cm-password-input>
                    <cm-form-field-error  key="fieldMatch" [message]="'Password doesnt match'"></cm-form-field-error>
                </cm-form-field>

                <cm-form-field>
                    <cm-input [type]="'password'" name="confirmPassword2" ngModel #confirmPassword2="ngModel" required [label]="'Confirm Password'" [theme]="'primary'">
                    </cm-input>
                    <cm-form-field-error key="fieldMatch" [message]="'Password doesnt match'"></cm-form-field-error>
                </cm-form-field>
        </form>

1 个答案:

答案 0 :(得分:2)

更改此行:

useExisting: forwardRef(() => FieldMatcherDirective)

并从@angular/core

导入

此外,由于您在构造函数中获取了ValidatorFn,因此无法使用。 field1和field2输入将始终是未定义的,因为它们是在调用ngOnChanges挂钩之前设置的。而是将代码移至ngOnChanges,如下所示:

ngOnChanges() {
    this.validator = fieldMatcherValidator(this.field1, this.field2);
  }

然后将validate()方法更改为此:

validate(control: AbstractControl) {
    return this.validator ? this.validator(control) : null;
  }