Building a React component that validates required form fields

Aleksander Sekowski
2 min readMar 12, 2020

--

In my previous article, we have written a js script that automatically detects all required fields in a form and highlights them.

We also added that script to a material-ui react form. Integration was done by running the validator function on the submit button event handler.

For react though, there are neater ways to integrate that kind of functionality. Let’s build a react component that will wrap the form, capture submit action, validate the form and continue or break.

So what should it look like?

Our react component should have the following features:

  • be aware of all required fields
  • be aware of the submit button and when the user interacts with it
  • make sure the user won’t progress until all required fields are filled in
  • find, highlight and scroll to empty required fields on submit button click

And all of this will be at your disposal simply by wrapping your form with a

<FormValidator>{* your form here *}</FormValidator>

We are already halfway there

A good developer will always re-use the code he has written and tested before when possible and avoid duplication. We will use this script to get most of the functionality we need.

And quite simply, our component will look like this:

So let’s look into it more closely

We will add a constructor to the component class so that we can create a body reference.

constructor(props) {
super(props);
this.body = React.createRef();
}

The render function is passed “children” as props and we will use a “div” to create a wrapper — with a ref set on it so we can use it to look up the DOM tree:

render() {
const { children } = this.props;
return <div ref={this.body}>{children}</div>;
}

The main part of the action will happen in the “componentDidMount” lifecycle method. We know all our components are mounted by that point, so we can reference them, first finding the submit button for our form

const submitButton = this.body.current.querySelectorAll(‘[type=”submit”]’ );

and then initialize our validator function.

const validator = form8or({ highlightAll: true });

The last and most important part is attaching a click event handler to the submit button. In there we will trigger the validator function

const remainingFields = validator.validate();

and in case some required fields are not filled, we have to stop the browser from proceeding with the click event by canceling it like

if (!!remainingFields.length) {
e.preventDefault();
e.stopImmediatePropagation();
}

Conclusion

Last week we built a validator script. This week we wrapped it in a react component. We are getting closer to creating better forms for our users 😃

--

--

Aleksander Sekowski
Aleksander Sekowski

No responses yet