antd Form 校验 加入自定义复杂逻辑
javascript
<Form.Item
label="编码"
name="code"
rules={[
{
required: true,
validator: (_rule, value) => {
if (value === '') {
return Promise.reject('请输入编码');
}
return IsExist(value).then((res) => {
if (res?.statusCode === 200) {
return Promise.resolve();
} else {
//return Promise.reject(res?.message);
//调用接口考虑接口报错提示
return Promise.reject("编码已经存在,请重新输入");
}
}).catch(err=>{
return Promise.reject(err?.message);
});
},
},
]}
>
<Input maxLength={50} />
</Form.Item>
写出方法:
validateLimit 方法:
javascript
const validateLimit = async (rule, value) => {
console.log(rule, value, !!value.trim());
if (!!value.trim()) {
return Promise.resolve();
} else {
return Promise.reject(new Error('不能输入空格!'));
}
};
javascript
<Form.Item
name="name"
rules={[
{ required: true, message: '请输入名称' },
{ validator: validateLimit },
// {
// pattern: /^(?!\s)(?!.*\s$)/,
// message: '首尾不能输入空格',
// },
]}
>
<Input
bordered={false}
placeholder="请输入"
style={{ textAlign: 'center' }}
/>
</Form.Item>