为年龄输入框添加了两个验证,并分状况填写了提示语html
年龄请输入年龄年龄必须为数字,且大于等于0
[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
编码请输入编码已存在相同编码
设置表单验证
Tip:[默认值,[同步校验],[异步校验]]
这里this.checkData是异步校验,因此写到第三个参数的位置后端
this.validateForm = this.fb.group({ code: [null, [Validators.required], [this.checkData]], // 编码 });
调用testService的方法,异步查询结果api
/** * @description 自定义表单验证:查询编码是否重复 */ checkData: AsyncValidatorFn = (control: FormControl): Promise=>{ 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{ // 这里能够调用服务,验证是否存在相同编码 // 例子简化为前端验证 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