前端表单验证
为年龄输入框添加了两个验证,并分情况填写了提示语
<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);
});
}