Angular 2+ Reactive Forms - Custom Validation

How to create a custom validator in Angular.

May 14, 2018

Complicated Problem 2: I need custom validation rules

Angular is super nice and gives us some basic validators out of the box.

  const control = new FormControl('some value', {
    validators: Validators.required
  });

//min(), max(), required(), requiredTrue(), email(), minLength(),
//maxLength(), pattern(), nullValidator(), compose(), composeAsync()

We can also handle validation with patterns a few different ways … I prefer the later cause I know not everyone loves Regexes as much as me, so I can give them reasonable sounding variable names. Also cause I can barely remember what I ate for breakfast, let alone a regex I wrote 2 weeks ago.

const control = new FormControl('some value', {
	validators: Validators.pattern('[0-9]{5}')
});

const myDatePattern = "^\\d{2}\/\\d{2}\/\\d{4}$";
const otherControl = new FormControl('some value', {
  validators: Validators.pattern(myDatePattern)
});

psssst, note the double escaping - the Regex needs a string representation of \d. This trolled the crap out of me at one point in time

Moving on, we also have function validation, for those tricky times you need validation based on dynamic content!

amountValidator(c: FormControl) {
  return c.value > 340 ? null : {
    validAmount: {
      valid: false
    }
  };
}
const control = new FormControl('some value', {
  validators: [Validators.required, amountValidator]
});

Between these validation methods, we can take on any complicated problem business requirements throw our way!

Demo code available at https://github.com/tehfedaykin/complicated-forms-app