简体   繁体   English

如何正确验证和提交表单是否与带有TypeScript的ant design表单有效

[英]How to correctly validate and submit if form is valid with ant design form with typescript

I build a simple form with react, redux, typescript ant design. 我用react,redux,typescript ant设计构建了一个简单的表单。 Following the ant design documentation, I created a small form using the provided getFieldDecorator and Form.create methods. 按照ant设计文档,我使用提供的getFieldDecoratorForm.create方法创建了一个小表单。 Everything works fine so far and validation is handled by ant design itself when entering data into the fields. 到目前为止,一切工作都很好,并且在将数据输入字段时,验证由蚂蚁设计本身来处理。 My main issue is with the form submit. 我的主要问题是表单提交。 I want to submit data only if the form is validated and the form is, therefore "valid". 我只想在表单经过验证且表单为“有效”的情况下提交数据。

The official documentation uses validateFields to validate the form and returns a variable which contains the errors and returns further execution so that the form doesn't get submitted. 官方文档使用validateFields来验证表单,并返回包含错误的变量并返回进一步执行,以使表单不会被提交。 Now with typescript I have the following signatures: validateFields(): void; 现在使用打字稿,我具有以下签名: validateFields(): void; <- I use this method to trigger validation upon submit of the form and afterwards call getFieldsError(names?: Array<string>): Record<string, string[] | undefined>; <-我使用此方法在提交表单时触发验证,然后调用getFieldsError(names?: Array<string>): Record<string, string[] | undefined>; getFieldsError(names?: Array<string>): Record<string, string[] | undefined>;

Now if you look at the example code, the ugly part is using a variable "allValid" to check if the form is valid or not. 现在,如果您查看示例代码,则丑陋的部分正在使用变量“ allValid”来检查表单是否有效。 I thought there must be a simpler way of validating and submitting data if the form is valid. 我认为,如果表格有效,则必须有一种更简单的方法来验证和提交数据。

const UploadForm: FunctionComponent<FormComponentProps> = props => {
  const { getFieldDecorator, validateFields, getFieldsError } = props.form;
  const dispatch = useDispatch();

  return (
    <Form
      {...formItemLayout}
      onSubmit={event => {
        event.preventDefault();
        validateFields();
        const validationErrors = getFieldsError();
        let allValid = true;
        console.log(validationErrors);
        for (let key in validationErrors) {
          console.log(validationErrors[key]);
          if (validationErrors[key] !== undefined) {
            allValid = false;
            break;
          }
        }

        if (allValid) {
          dispatch(submitFormData());
        }
      }}
    >
      <ImageComponent />
      <Form.Item label="E-mail">
        {getFieldDecorator("email", {
          rules: [
            {
              type: "email",
              message: "The input is not valid E-mail!"
            },
            {
              required: true,
              message: "Please enter your E-mail!"
            }
          ]
        })(
          <Input
            prefix={<Icon type="mail" style={{ color: "rgba(0,0,0,.25)" }} />}
            placeholder="Your e-mail"
          />
        )}
      </Form.Item>
      <Form.Item {...buttonItemLayout}>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
  );
};

export default Form.create < FormComponentProps > {}(UploadForm);

You can use Object.values() and Array.find() to find the undefined value. 您可以使用Object.values()Array.find()查找undefined值。

validateFields();
const validationErrors = Object.values(getFieldsError());

if (!validationErrors.find(e => e === undefined)) dispatch(submitFormData());

Or you can disable the submit Button . 或者,您可以禁用Submit Button

Validate each Form.Item , and allow submitting only when all validation status is success . 验证每个Form.Item ,并仅在所有验证状态为success时才允许提交。

<Button
  type="primary"
  htmlType="submit"
  disabled={!(validateEmptyField(name) && validateEmptyField(surName))}
>
  Submit
</Button>;

Use validateStatus to validate each Form.Item : 使用validateStatus验证每个Form.Item

function FromValidate() {
  const [name, setName] = useState('');
  const [surName, setSurName] = useState('');

  return (
    <Flexbox>
      <Form
        onSubmit={e => {
          e.preventDefault();
          console.log('name', name);
          console.log('surName', surName);
        }}
      >
        <Form.Item
          label="Name"
          required={true}
          validateStatus={validateEmptyField(name) ? 'success' : 'error'}
          help={!validateEmptyField(name) && 'Name cannot be empty'}
        >
          <Input
            placeholder="Unique Identifier"
            value={name}
            onChange={e => setName(e.target.value)}
          />
        </Form.Item>
        ...
        <Form.Item>
          <Button
            type="primary"
            htmlType="submit"
            disabled={
              !(validateEmptyField(name) && validateEmptyField(surName))
            }
          >
            Submit
          </Button>
        </Form.Item>
      </Form>
    </Flexbox>
  );
}

编辑表单验证

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM