[React]antd表单校验函数写法

来自文心一言

通过 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 @ 2024-11-29 17:24  夕苜19  阅读(5)  评论(0编辑  收藏  举报