Client side validation errors

Linked Projects:

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.

Liked this tutorial? Get more like this in your inbox