Client side validation errors

This video was part of the The Complete React on Rails 5 Course.

A new version of the course is now available

Enroll now to view this video

Lesson code -

Next, let’s add validation error messages on the client side.

First, let’s declare a fieldErrors variable under the existing fieldValid variable.

let fieldValid;
let fieldErrors;

Then we will add:

case 'title':
  fieldValid = this.state.title.value.trim().length > 2;
  if(!fieldValid) {
    fieldErrors=[' should be at least 3 characters long'];

Now let’s do the same for appt_time.

case 'appt_time':
  fieldValid = moment(this.state.appt_time.value).isValid() &&
  if(!fieldValid) {
    fieldErrors=[' should not be in the past'];

And then we’ll take that field error and update the formErrors value in the state.

First, let’s create a new const newFormErrors with the immutability helper method update.

const newFormErrors = update(this.state.formErrors,
                              {$merge: {[fieldName]: fieldErrors}});

Then we can use it our setState call.

this.setState({[fieldName]: newFieldState},
                formErrors: newFormErrors}, this.validateForm);

Then we can refresh the app to see if it works.

Now the form errors work on the client side too, for both title and appt_time.

But we also need to clear the errors, so that they disappear when we choose a valid value.

We need to set the initial value of fieldErrors to an empty array.

let fieldErrors = [] ;

Now if we try again, it should work properly. The error messages appear when the values are invalid and disappear when the values are valid, and the button also gets enabled or disabled accordingly.

So that’s our validation with error messages working completely on the client side.

This lesson was part of the The Complete React on Rails 5 Course.

A new version of the course is now available

Get the full course

You're viewing a lesson from an old course. Click here to get access to the new version.