NG_VALIDATORS

一个 InjectionToken,用于注册额外的同步验证器,供 AbstractControl 使用。

An InjectionToken for registering additional synchronous validators used with AbstractControls.

const NG_VALIDATORS: InjectionToken<(Function | Validator)[]>;
      
      const NG_VALIDATORS: InjectionToken<(Function | Validator)[]>;
    

参见

使用说明

提供自定义验证器

Providing a custom validator

下面的例子注册了一个自定义验证器指令。要把该验证器添加到现存的验证器集合中,需要使用 multi: true 选项。

The following example registers a custom validator directive. Adding the validator to the existing collection of validators requires the multi: true option.

@Directive({ selector: '[customValidator]', providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}] }) class CustomValidatorDirective implements Validator { validate(control: AbstractControl): ValidationErrors | null { return { 'custom': true }; } }
      
      @Directive({
  selector: '[customValidator]',
  providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}]
})
class CustomValidatorDirective implements Validator {
  validate(control: AbstractControl): ValidationErrors | null {
    return { 'custom': true };
  }
}