ts部分:
//引入指令需要的相关包
import {Directive} from '@angular/core';
import {AbstractControl, NG_VALIDATORS, Validator, ValidatorFn} from '@angular/forms';
//定义名字
@Directive({
selector: '[phoneValidator]',
providers:[{provide: NG_VALIDATORS, useExisting: PhoneValidatorDirective, multi:
true}]
})
//定义指令
export class PhoneValidatorDirective implements Validator {
validate(control: AbstractControl):{ [key: string]: any }{
return control.value ? phoneCheck(new RegExp(/^1[3-9][0-9]{9}$/,'i'))(control) : null
}
//需要判断规则的函数
export function phoneCheck(nameRe: RegExp): ValidatorFn{
return (control:AbstractControl) :{ [key: string]: any } =>{
if(control.value <0){
return {min: true};
}else if(!nameRe.test(control.value)){
return {invalid: true};
}else {
return null;
}
}
}
html部分:
<div nz-form-label>
<label for="phone" nz-form-item-required>手机号</label>
</div>
<div nz-form-control>
<input formControlName="phone" phoneValidator>
<div nz-form-explain *ngIf="getFormControl('phone').dirty">
<span *ngIf="getFormControl('phone').hasError('invalid')">请输入正确的手机号码
</span>
</div>
</div>