Sometimes you have to take matters into your own hands. Even when it comes to validating forms in your Angular app.

In other words, it's not always good enough to let Angular do the validating for you. You need to do it programmatically.

One good use case for that is the "final pass" just before a user submits a form. In that case, you want to make sure that all the fields on the form are valid before sending everything to the downstream service.

And that's a great time to use the updateValueAndValidity() method. In this guide, I'll show you how to do it.

One Last Check

Let's say you've got a CRM app that allows sales reps to create activities for various contacts. You've got several fields on the form that follow validation rules.

Normally, a rule for a specific field gets triggered every time the user tabs away from the field. At least that's the way it works for client-side validation.

But you want to perform One Last Check when the user clicks the submit button. It's another pass over the fields just to make absolutely certain that all of them pass validation.

That kind of thing is easy to implement with updateValueAndValidity(). 

But What Exactly Is That Method?

The updateValueAndValidity() method belongs to the AbstractFormControl class. The whole point of the method is to recalculate the value as well as the validation status of the field.

That method, by the way, accepts a couple of parameters. But they're optional. You can just go with empty parentheses.

And that's what you'll do here because you don't need to set any of the optional parameters. Maybe I'll go over those in a different article.

The Validity Code

In the activity-form.component.ts class, add this little bit to the saveActivity() method.

    Object.keys(this.activityFormGroup.controls).forEach(field => {
      let control = this.activityFormGroup.get(field);
      control.updateValueAndValidity();
    });

Here's what that code does: it steps through each control field in activityFormGroup. That's the variable name of the FormGroup object that holds all the fields in the activity form.

For each one of those fields, the code invokes the updateValueAndValidity() method. That's going to force a revalidation of the field.

So just in case something got missed when the user initially filled out the form, the code here will catch the problem.

In that case, the user will see a warning about the error so he or she can take corrective action.

That saveActivity() method, by the way, is the method that gets invoked when the user clicks the... wait for it... Save Activity button.

The next block of code handles the rest:

    if (this.formService.formHasErrors(this.activityFormGroup)) {
      this.alertService.error("Form contains errors. See below.");
      this.scrollToTop();
      this.saving = false;
    } else {
      this.setActivity();

      if (!this.activity.id) {
        this.activityService.createActivity(this.activity).subscribe(
          (activity: Activity) => this.handleActivitySaveResponse(activity),
          err => this.handleActivitySaveError(err)
        );
      } else {
        this.activityService.updateActivity(this.activity).subscribe(
          (activity: Activity) => this.handleActivitySaveResponse(activity),
          err => this.handleActivitySaveError(err)
        );
      }
    }

That if statement checks if the form has errors. If so, then it shows an alert informing the user that there are problems. That user will see individual problem messages on each field that didn't pass validation.

If there are no errors, though, then the code proceeds to persist the activity info.

Wrapping It Up

And that's it. If you want to do one final sanity check on your forms before sending them off to the back end, use updateValueAndValidity(). It's as easy as pie.

However, you might find other uses for that same method in your own business requirements.

But no matter which way you decide to use it, just be sure to have fun!

Photo by RODNAE Productions from Pexels