填写这份《一分钟调查》,帮我们(开发组)做得更好!去填写Home

Validator

一个接口,实现了它的类可以扮演验证器的角色。

An interface implemented by classes that perform synchronous validation.

      
      interface Validator {
  validate(control: AbstractControl): ValidationErrors | null
  registerOnValidatorChange(fn: () => void)?: void
}
    

方法

Method that performs synchronous validation against the provided control.

validate(control: AbstractControl): ValidationErrors | null
      
      validate(control: AbstractControl): ValidationErrors | null
    
参数
control AbstractControl

The control to validate against.

返回值

ValidationErrors | null: A map of validation errors if validation fails, otherwise null.

Registers a callback function to call when the validator inputs change.

registerOnValidatorChange(fn: () => void)?: void
      
      registerOnValidatorChange(fn: () => void)?: void
    
参数
fn () => void

The callback function

返回值

void

使用说明

提供一个自定义的验证器

Provide a custom validator

下面的例子实现了 Validator 接口,以便用一个自定义的错误键来创建验证器指令。

The following example implements the Validator interface to create a validator directive with a custom error key.

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