Can Ant Design form validation be skipped upon clicking the submit button?

Viewed 1787

When submitting an AntD form (initiated by clicking submit button) it seems to run through validation of fields by default. I am tracking validation with each form field change so it is unnecessary for my implementation.

Is there a baked-in way to skip/disable the form validation upon submission of the form in Ant Design?

2 Answers

If you don't give Button type submit, and add an onClick method (handleSubmit below) to the button, you can handle submitting on button click without form validation being run automatically.

import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Form, Input, Button, Checkbox } from "antd";
const layout = {
  labelCol: {
    span: 8
  },
  wrapperCol: {
    span: 16
  }
};
const tailLayout = {
  wrapperCol: {
    offset: 8,
    span: 16
  }
};

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

  const handleSubmit = (e) => {
    // grab form values
    let form_vals = form.getFieldsValue();
    // perform the rest of submit logic here...
  };

  return (
    <Form
      form={form}
      {...layout}
      name="basic"
      initialValues={{
        remember: true
      }}
    >
      <Form.Item
        label="Username"
        name="username"
        rules={[
          {
            required: true,
            message: "Please input your username!"
          }
        ]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="Password"
        name="password"
        rules={[
          {
            required: true,
            message: "Please input your password!"
          }
        ]}
      >
        <Input.Password />
      </Form.Item>

      <Form.Item {...tailLayout} name="remember" valuePropName="checked">
        <Checkbox>Remember me</Checkbox>
      </Form.Item>

      <Form.Item {...tailLayout}>
        <Button type="primary" onClick={handleSubmit}>
          Submit
        </Button>
      </Form.Item>
    </Form>
  );
};

antd version: 4.10

AntD (4.17.0) introduced the warningOnly property for validation rules. If it is set to true, the form can be submitted even if that rule is violated.

Result: Orange warning will be shown in the UI (as opposed to red for an error) and the form will submit successfully.

Ref: https://codesandbox.io/s/mfm92l

Related