[Ant Design] Validator implements callback and Promise methods for custom form submission rules

Scenes

Form provides us with a lot of convenience for form submission, and various properties can come in handy.
Now if we want to implement a custom rule, we can block the submission of the form through callback or Promise.

Callback method

<Form.Item
    hasFeedback
    rules={
    
    [
        {
    
    
            validator: async (rule, value, callback)=>{
    
    
                // 请求判断用户是否存在
                let res = await that.certificate(value);
                if(res.status === 1)
                    callback('用户名已存在');
                else callback();
            },
        }
    ]}
>
</Form.Item>

But in fact, promis is more controllable, because callback needs to be called eventually regardless of the process. callback('xxx'') means that the verification has not passed, and callback() means that the verification has passed , but if you Add the attribute of hasFeedback, you will find that as long as the callback is

Promise method

<Form.Item
    hasFeedback
    rules={
    
    [
        {
    
    
            validator: async (rule, value)=>{
    
    
                // 请求判断用户是否存在
                let res = await that.certificate(value);
                if(res.status === 1)
                    return Promise.reject('用户名已存在');
                else return Promise.resolve('用户名可用');
            },
        }
    ]}
>
</Form.Item>

Guess you like

Origin blog.csdn.net/weixin_42339197/article/details/110679631