【问题标题】:Is it possible to use `class-validator` with antd `Form.useForm`()?是否可以将 `class-validator` 与 antd `Form.useForm`() 一起使用?
【发布时间】:2022-01-10 11:32:56
【问题描述】:

我用class-validator创建了一个DTO对象:

export class CreateItemDto {
  @IsString()
  @Length(2, 63)
  readonly name: string;
}

是否可以在 Ant Design 的Form.useForm() 中使用它,或者我必须自己创建如下规则?

const [form] = Form.useForm<CreateItemDto>();

return (
  <Form form={form}>
    <Form.Item
      label="Name"
      name="name"
      rules={[{
        required: true,
        message: t('Please enter correct name'),
        min: 2,
        max: 63,
      }]}
    >
      <Input />
    </Form.Item>
  </Form>
)

【问题讨论】:

    标签: reactjs typescript forms antd class-validator


    【解决方案1】:

    我认为 antd 默认不支持使用class-validator 验证表单。您可以尝试手动运行 class-validator validate 函数并通过自定义验证器规则将其连接以形成规则。

    https://codesandbox.io/s/registration-antd-4-17-3-forked-5x92w?file=/index.js:0-1142

    import React from "react";
    import ReactDOM from "react-dom";
    import "antd/dist/antd.css";
    import "./index.css";
    import { Form, Input } from "antd";
    import { validate } from 'class-validator';
    import { CreateItemDto } from "./CreateItemDto";
    
    const RegistrationForm = () => {
      const [form] = Form.useForm();
    
      return (
        <Form
          form={form}
          name="register"
        >
          <Form.Item
            name="name"
            label="Name"
            hasFeedback
            rules={[
              {
                validator: async (_, value) => {
                  const dto = new CreateItemDto({
                    name: value
                  });
    
                  let errors = await validate(dto, {
                    skipMissingProperties: true
                  });
    
                  if (errors?.length > 0) {
                    console.log(errors);
                    return Promise.reject(new Error('Validation errors'));
                  } else {
                    return Promise.resolve();
                  }
                }
              }
            ]}
          >
            <Input />
          </Form.Item>
        </Form>
      );
    };
    
    ReactDOM.render(<RegistrationForm />, document.getElementById("container"));
    
    import {
      Length,
      IsString
    } from 'class-validator';
    
    export class CreateItemDto {
      @IsString()
      @Length(2, 4)
      name: string;
    
      constructor({ name }: { name: string}) {
        this.name = name;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-04-12
      • 2022-06-22
      • 1970-01-01
      • 2022-01-07
      • 2021-11-12
      • 2016-04-01
      • 2011-01-20
      • 2018-08-11
      • 2021-08-05
      相关资源
      最近更新 更多