this.options = new FormBuilder().group({
Email: new FormControl({value: '' , disabled: true}, [emilChValidator(/.*[\u4e00-\u9fa5]+.*$/)] ), 邮箱
});
<form [formGroup]="options">
<mat-form-field appearance="outline" >
<input matInput autocomplete="off" value="" formControlName="Email">
<mat-error *ngIf="options.hasError('forbiddenChNo' , 'Email')"> {{options.getError('forbiddenCh' , 'Email')}}</mat-error>
</mat-form-field>
</form>
export function emilChValidator(nameRe: RegExp): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} | null => {
if (!control.value) {
const er_ = { forbiddenCh: '邮箱地址为必填项' , forbiddenChNo: true};
return er_;
}
const forbidden = nameRe.test(control.value);
const err_ = forbidden === true ? { forbiddenCh: '不能为汉字' , forbiddenChNo: true} : null;
// 记录一下,如果没有包含任何情况就返回一个null,这个时候表单验证才会消失框框才不会是红色的。这个地方我栽了坑,磨了很长时间,之前一直返回一个false。
return err_;
};
}