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