Files
geg-gas-web/docs/表单二开/7_自定义校验.md
2024-08-21 17:15:52 +08:00

43 lines
1.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 如何实现表单自定义校验
下面的例子介绍如何为字段增加自定义校验校验的条件是两个文本框内的数字之和必须大于100。任何多字段的校验都可以参照此进行日期时间可以借助dayjs库比较。
首先在config.ts里加入设置表单用的函数以便我们在自定义校验中可以拿到全部表单的值。
```javascript
let formRef = null;
export function setFormRef(ref) {
formRef = ref;
}
```
然后再Form.vue中将表单的引用传到config.ts里
```javascript
// setFormRef要引入进来
import { formProps, formEventConfigs, setFormRef } from './config';
const systemFormRef = ref();
setFormRef(systemFormRef); //新加的
```
最后就可以编写校验规则的代码找到需要触发校验的字段在rules里增加自定义规则。
validator可以是异步函数因此通过接口验证也可以。默认参数为_rule: Rule, value: string如果是单值校验可以不引入表单引用直接在校验器拿值。
```javascript
{
rules: [{
validator: async function() {
const formValues = formRef.value.getFieldsValue();
const val1 = formValues.zhaGe15916;
const val2 = formValues.zhaGe22645;
if (!val1 || !val2) {
return Promise.resolve(); // 这里需要搭配必填校验
}
if ((+val1) + (+val2) != 100) {
return Promise.reject('两数之和必须为100');
}
return Promise.resolve();
},
trigger: 'blur'
}]
}
```