为年龄输入框添加了两个验证,并分状况填写了提示语html
<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的验证规则git
/** * @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,则验证失败github
<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的方法,异步查询结果api
/** * @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,不存在,返回falsepromise
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); }); }
示例代码app