Orbit
Orbit

Reputation: 2395

Form validation with Form component

I am unsure on how to do form validation with the antd <Form/> component found here. The documentation specifies an onSubmit prop on the <Form/> component, which is passed an event. It then seems to trigger a function inside this.props.form. I am currently using the following code:

handleSubmit(e) {
   e.preventDefault();

  console.log('before' + e.target.value)

  this.props.validateFields((err, values) => {
  console.log('errors: ' + err)
  console.log(values)
    if (!err) {
      console.log('Received values of form: ', values);
    }
  });
}

<Form inline onSubmit={this.handleSubmit.bind(this)}>
    ....
</Form>
  1. I am unable to retrieve values from the event passed into the submit callback, as e.target.value returns undefined.

    1. In the call to this.props.validateFields(), as shown in the documentation, where are these values coming from?

Upvotes: 1

Views: 5308

Answers (2)

Jaison James
Jaison James

Reputation: 4552

I know it's very late also not sure you had the same issue. but recently I had the issue like form values are not getting for me. So I have used below code and its working fine for me. May it will help someone else.

handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
        if (err) {
            return;
        }

        alert(JSON.stringify(values));
    });
}

and in the form

<Form onSubmit={this.handleSubmit}>

Upvotes: 0

Yichz
Yichz

Reputation: 9681

The whole form data is managed by antd Form component, So you don't need to get then by e.target.value, what you need is to call

this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
      }
    });

When ever you want to do the validation. this callback provides you if there is an error or the full set of form data.

values comes from the form props which is injected by Form.create();

this.props.form is also injected by Form.create(), otherwise you will get undefined, eg:

class MyComponent extends React.Component {
...
}

export default Form.create()(MyComponent);

You can also use validateFieldsAndScroll instead of validateFields which will automatically scroll to the field where an error is ocurred.

Upvotes: 5

Related Questions