[React]AntDesign自定义表单校验函数写法

来自文心一言

通过 rules 属性来定义校验规则,其中可以包含自定义的校验函数 validator

复制代码
import React from 'react';
import { Form, Input, Button } from 'antd';

const MyForm = () => {
  const [form] = Form.useForm();

  // 自定义校验函数
  const checkUsername = (_, value) => {
    if (!value) {
      return Promise.reject(new Error('用户名不能为空'));
    }
    if (value.length < 3) {
      return Promise.reject(new Error('用户名长度不能少于3个字符'));
    }
    return Promise.resolve();
  };

  const onFinish = (values) => {
    console.log('Success:', values);
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <Form
      form={form}
      name="basic"
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 16 }}
      initialValues={{ remember: true }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      <Form.Item
        label="用户名"
        name="username"
        rules={[
          { required: true, message: '请输入用户名!' },
          { validator: checkUsername }  // 使用自定义校验函数
        ]}
      >
        <Input />
      </Form.Item>

      <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
        <Button type="primary" htmlType="submit">
          提交
        </Button>
      </Form.Item>
    </Form>
  );
};

export default MyForm;
复制代码

 

posted @   夕苜19  阅读(54)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示