简体   繁体   中英

Custom validation for custom fields in React

I have a form, which is populated using various types of question fields (eg text input, email, number, radio box, tags, custom inputs ). These field types are fetched dynamically based on prior choices of user on a previous form.

Now, I have to validate the different form fields when user submits the form using React. The issue is that I can't simply check the value attribute of the fields, since some fields are complex and we get the value after applying some calculation, replacing-non-numbers, or some fields may have radio buttons and corresponding text inputs etc. How can I go about this validation in React? My general structure is this:

<form>
  { this.props.questions.map((question, index) => {
    return <Question key={index} data={question} validationError={this.state.validationErrors[question.name]} />
  })}
</form>
<button onClick={this.validateFields}>Submit</button>

Is it possible to loop through components in validateFields method of this component class? Or I need to loop through the html nodes that are rendered in the final HTML? Earlier I was doing this using jQuery and was looping through the question div elements and applying custom validation rules depending on the question type (stored in a data attribute).

Now, I am not sure what is the correct way to do this in React.

You're applying jQuery (and vanilla JS) patterns of thinking to React. I suggest to stop considering you have DOM in any form. No DOM, no components list either, do not touch it or React will be a pain instead of help.

All the data you want to have must be in state. That's the purpose of this library.

So, in your case it is better to go this way:

1) Implement onChange event in Question and other field components. Regardless of how complex they are, your could stream their data into a signle argument, aren't you?

2) Add onChange handler in your form with something like

onChange={value => 
    this.setState({ 
        fieldValues: { 
            [index]: value 
        }
    })
}

3) Populate fieldValues like this:

constructor(props) {
    super(props);
    this.state = {
        fieldValues: props.questions,
    };
}

And voila - all the form data are already in this.state.fieldValues , ready for any ongoing usage.

Surprised? So I was, when I first been understanding user input in React. Check this section in React docs for the source of the idea: https://reactjs.org/docs/forms.html#controlled-components

您可以在这里找到复杂的示例https://medium.com/@krzakmarek88/complex-form-validation-in-react-hooks-cb07367196b9也许会对您有所帮助。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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