我正在处理一个表单(Ant Design
<Form>
),在该表单中我需要对电话号码进行自定义验证(因为它取决于country
字段并具有一些额外的逻辑),其他字段通过antd
内置功能进行了验证,因此,当用户提交表单时,我希望所有validateFields()
的字段都通过字段名数组来验证所有字段,这些字段名和往常一样显示验证错误(控制台中的错误消息),但我得到的只是控制台中的警告消息。
这是最小复制品
我是否缺少有关validator
函数如何工作的信息?
答案 0 :(得分:1)
进行if if检查,如果value不为空,则检查validatePhone函数,然后运行您的代码,如果value为空,只需在else条件下发送回调。这样
const validatePhone = (rule: any, value: any, callback: any) => {
if(value){
const countryName = form.getFieldValue('country');
const country = CountryList.getCode(countryName);
const phoneNumber = parsePhoneNumberFromString(value, country as CountryCode);
console.log(form.getFieldValue('country'));
if (countryName && phoneNumber && phoneNumber.isValid()) {
updatePhonePrefix(prefix.concat(phoneNumber.countryCallingCode as string));
callback();
} else {
callback(`Phone number is not valid for ${countryName}`);
}
}else{
callback()
}
};
答案 1 :(得分:0)
antd docs建议使用异步或try-catch块
选项1:
const validatePhone = async (rule, value) => {
// check failing condition
throw new Error('Something wrong!');
}
选项2:
const validatePhone = (rule, value, callback) => {
try {
throw new Error('Something wrong!');
} catch (err) {
callback(err);
}
}
答案 2 :(得分:0)
这里我是如何处理 antd 形式的错误
import React, { useState } from 'react';
import { Form, Input } from 'antd';
function MyCustomForm(props: any) {
const [form] = Form.useForm();
const [validateFieldsName, setValidateFieldsName] = useState<string[]>([]);
const handleValidateFieldNames = (name: string) => {
const isFieldName = validateFieldsName.find(
(fieldName) => fieldName === name
);
if (isFieldName) return 'onChange';
return 'onBlur';
};
return (
<Form form={form} layout="vertical">
<Form.Item
name="contactNumber"
label="Contact Number"
validateTrigger={handleValidateFieldNames('contactNumber')}
rules={[
{
required: true,
message: 'Please enter contact number!',
},
{
validator(_, value) {
if (!value || value.length === 10) {
return Promise.resolve();
}
return Promise.reject('Please enter 10 digit Number!');
},
},
]}
>
<Input
type="number"
placeholder="Contact number"
onBlur={() =>
setValidateFieldsName([...validateFieldsName, 'contactNumber'])
}
/>
</Form.Item>
</Form>
);
}
export default MyCustomForm;