前端表單驗證
為年齡輸入框添加了兩個驗證,並分情況填寫了提示語
<form nz-form [formGroup]="validateForm">
<nz-form-item>
<nz-form-label [nzSpan]="3" nzRequired>年齡</nz-form-label>
<nz-form-control [nzSpan]="8" nzHasFeedback>
<input nz-input formControlName="age" placeholder="請輸入年齡">
<nz-form-explain *ngIf="validateForm.get('age').dirty && validateForm.get('age').errors">
<ng-container *ngIf="validateForm.get('age').hasError('required')">請輸入年齡</ng-container>
<!--自定義驗證 注意加單引號-->
<ng-container *ngIf="validateForm.get('age').hasError('isMoreThanZero')">年齡必須為數字,且大於等於0</ng-container>
</nz-form-explain>
</nz-form-control>
</nz-form-item>
</form>
[Validators.required, this.isMoreThanZero]為age字段的驗證列表
其中Validators.required是Validators提供的驗證,this.isMoreThanZero是自定義驗證
this.validateForm = this.fb.group({
age: [null, [Validators.required, this.isMoreThanZero]], // 年齡
});
自定義isMoreThanZero的驗證規則
/**
* @description 自定義表單驗證:是數字並且大於等於0
*/
isMoreThanZero = (control: FormControl) => {
if (!control.value) {
return { required: true };
} else if (isNaN(Number(control.value)) || control.value < 0) {
// 注意,這里返回的是isMoreThanZero,才能對應.hasError('isMoreThanZero')
return { isMoreThanZero: true };
}
}
后端表單驗證
比如,業務要求編碼不重復,查詢編碼是否存在
設置一個叫做existSameCode的驗證,當existSameCode=true,則驗證失敗
<nz-form-item>
<nz-form-label [nzSpan]="3" nzRequired>編碼</nz-form-label>
<nz-form-control [nzSpan]="8" nzHasFeedback>
<input nz-input formControlName="code" placeholder="請輸入編碼">
<!--表單驗證-->
<nz-form-explain *ngIf="validateForm.get('code').dirty && validateForm.get('code').errors">
<ng-container *ngIf="validateForm.get('code').hasError('required')">請輸入編碼</ng-container>
<ng-container *ngIf="validateForm.get('code').hasError('existSameCode')">已存在相同編碼</ng-container>
</nz-form-explain>
</nz-form-control>
</nz-form-item>
設置表單驗證
Tip:[默認值,[同步校驗],[異步校驗]]
這里this.checkData是異步校驗,所以寫到第三個參數的位置
this.validateForm = this.fb.group({
code: [null, [Validators.required], [this.checkData]], // 編碼
});
調用testService的方法,異步查詢結果
/**
* @description 自定義表單驗證:查詢編碼是否重復
*/
checkData: AsyncValidatorFn = (control: FormControl): Promise<ValidationErrors | null> =>{
return new Promise((resolve2) => {
setTimeout(() => {
this.testService.checkData({code:control.value})
.then((response: any) => {
if (response) {
resolve2({existSameCode: true});
} else {
resolve2(null);
}
});
}, 1500);
});
}
如果存在,返回true,不存在,返回false
checkData(params): Promise<any> {
// 這里可以調用服務,驗證是否存在相同編碼
// 例子簡化為前端驗證
const pRequest =new Promise(function(resolve, reject) {
let existCodeList=['1','2','3'];
if(existCodeList.indexOf(params.code) > -1){
resolve(true);
}
resolve(false);
}).then((ret: any) => {
return ret;
});
return Promise.race([this.requestHelperService.getTimeoutPromise(), pRequest]).catch(ret => {
this.requestHelperService.handleRequestError(ret, true);
});
}
