<input [(ngModel)]="user.mobile" #mobile="ngModel" autocomplete="off" type="tel" class="form-control" name="mobile" required maxlength="11"> <div *ngIf="mobile.errors"> <p *ngIf="mobile.errors.required">手机号必填</p> <p *ngIf="mobile.errors.pattern">手机号格式不正确</p> </div>
@Directive({
providers: [{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => RequiredValidator),
multi: true
}]
})
export class RequiredValidator {}
export class NgModel extends NgControl {
constructor(@Inject(NG_VALIDATORS) validators: Array<Validator|ValidatorFn>) {}
get validator(): ValidatorFn|null {
// 各种校验并返回结果
}
}
@Directive({
selector: '[user-mobile]',
exportAs: 'userMobile',
providers: [{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => UserMobileDirective),
multi: true
}]
})
export class UserMobileDirective {}
export class UserMobileDirective implements Validator {
validate(c: AbstractControl): { [key: string]: any; } {
let value: string = c.value || '';
if (!value.startsWith('159')) {
return {
mobile: {
msg: '手机号必须是159开头',
actualValue: value
}
};
}
return null;
}
}
<input user-mobile [(ngModel)]="user.mobile" #mobile="ngModel" autocomplete="off" type="tel" class="form-control" name="mobile" id="mobile" required maxlength="11">
<div *ngIf="mobile.errors">
<p *ngIf="mobile.errors.required">手机号必填</p>
<p *ngIf="mobile.errors.mobile">{{mobile.errors.mobile.msg}}</p>
</div>
@Directive({
selector: '[user-async]',
exportAs: 'userAsync',
providers: [{
provide: NG_ASYNC_VALIDATORS,
useExisting: forwardRef(() => UserAsyncDirective),
multi: true
}]
})
export class UserAsyncDirective implements Validator {
validate(c: AbstractControl): Observable<any> {
return c.valueChanges
// 去抖
.debounceTime(300)
// 抑制重复值
.distinctUntilChanged()
// 1、可以使用flatMap进行远程校验
// .flatMap(value => value)
// 2、本地模拟判断
.map((value: string) => {
if ([ '15900000001', '15900000002' ].includes(value)) {
return {
mobile: {
msg: '手机号为黑名',
actualValue: value
}
}
}
return null;
})
.first();
}
}
export class MyValidators {
static checkMobile(value: string): ValidationErrors|null {
return !value.startsWith('159') ? { mobile: { msg: '手机号必须是159开头' } } : null;
}
}
// 校验器类
export class UserMobileDirective implements Validator {
validate(c: AbstractControl): { [key: string]: any; } {
let value: string = c.value || '';
return MyValidators.checkMobile(value);
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有