Angular 2 – FormBuilder forms with multiple validation errors

In our recent Angular 2 form we had two pattern validation rules that overlapped in certain cases. However, we only wanted one validation error to be visible at a time.

For a simplified example, one checks that a name contained the phrase “leftlobed” while the other validates that it contains “left” – checkout this Plunk to get what I mean by typing your name…

We could have updated the [hidden] rules in the UI / markup to only show one message if the other’s error was false… But if those composition rules got complicated it would be tough to keep them in sync.

Instead, we created our own version of Validator.compose(ValidatorFn[]) that would only return the first validation error based on the order of declaration.

  
  static composeFirst(validators: ValidatorFn[]) {
    if (!validators || !validators.length) return null;

    return (control: FormControl) => {
      var errors = validators.map(v => v(control));
      var firstError = errors.find(e => {
        if (!e) return false;

        var keys = Object.keys(e);
        if (!keys.length) return false;

        var key = keys[0];
        return (e[key] === true || e[key]["valid"] === false);
      });

      return firstError || null;
    }
  }

You can see it in action at this subsequent Plunk by seeing what happens as you type “leftlobed”!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s