天天看點

angular自定義表單驗證器

由于内置驗證器無法适用于所有應用場景,有時候還是得建立自定義驗證器。

自定義指令去正則驗證經緯度的 度、分、秒

angular自定義表單驗證器
import { Directive, Input} from '@angular/core';
import { AbstractControl, NG_VALIDATORS, ValidatorFn, Validator} from '@angular/forms';
export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} | null => {
    const forbidden:boolean = nameRe.test(control.value);
    return !forbidden ? {msg: {value: control.value}} : null;
  }
}

@Directive({
  selector: '[appValidatePosition]',
  providers: [{ provide: NG_VALIDATORS, useExisting: ValidatePositionDirective, multi: true }]
})
export class ValidatePositionDirective implements Validator{
  @Input('appValidatePosition') validateCondition: string;
  // console.log('control',control)
  validate(control: