UX Design for Input Validation in React

There are several ways to do Input Validation in React. I recommend using plain JavaScript instead of bloated packages like redux-form.

Validation, the usual way

The following video shows how we validate an email field usually.

Validation, the usual way

In the above video, as soon as the user starts typing into the email field, the error message pops up. This is because we validate in onChange event.

Validation, a better design

Of late, I am working with an UX designer from Google. This blog post is a code example of his design in React.

  1. Disable the Submit button until all required fields are filled.
  2. Do validations (other than required) only on Submit button.
  3. Don’t do any validations in onChange handler.

There are some very good benefits to the design. It is easy to implement. Both the developer and the end-user know what to expect out of the UI. There is no flicker till the user clicks the Submit button.

The following video shows the new UX in action.

Validation – the better way

Some React code

All the code for our simple Email validation is available in the CodePen.

Display a form with an email field and a button.

render() {
  return (
    

Add an onChange handler to the email.


 this.setState({ email: e.target.value })}
/>

Disable the button when email field is empty.

render() {
  const { email } = this.state;
  const disabled = !email;
  return (
    
this.setState({ email: e.target.value })} />
); }

Validate the email (only) when user clicks the Submit button.

handleSubmit(e) {
  e.preventDefault();
  const { email } = this.state;
  const emailError = emailRegex.test(email) ?
  '' :
  'Please enter a valid email address';
  this.setState({ emailError });
  if (!emailError) {
    // do some action
  }
}

Display the error below the email input.

 this.setState({ email: e.target.value })} 
/>
 {emailError && 
{emailError}
}

Style the input and button appropriately.  The code is available in CodePen.

Related Posts

Leave a Reply

Your email address will not be published.