Reactive Forms Custom Validation

As useful as the built-in validators are, it is very useful to be able to include your own.Angular allows you to do just that, with minimal effort.

Let's assume we are using the same Login Form, but now we also want to test that our password has an exclamation mark somewhere in it.

app/login-form.component.ts

  1. function hasExclamationMark(input: FormControl) {
  2. const hasExclamation = input.value.indexOf('!') >= 0;
  3. return hasExclamation ? null : { needsExclamation: true };
  4. }
  5. password = new FormControl('', [
  6. Validators.required,
  7. hasExclamationMark
  8. ]);

A simple function takes the FormControl instance and returns null if everything is fine.If the test fails, it returns an object with an arbitrarily named property.The property name is what will be used for the .hasError() test.

app/login-form.component.ts

  1. <!-- ... -->
  2. <div [hidden]="!password.hasError('needsExclamation')">
  3. Your password must have an exclamation mark!
  4. </div>
  5. <!-- ... -->

View Example

Predefined Parameters

Having a custom validator to check for exclamation marks might be helpful, but what if you need to check for some other form of punctuation?It might be overkill to write nearly the same thing over and over again.

Consider the earlier example Validators.minLength(5).How did they get away with allowing an argument to control the length, if a validator is just a function?Simple, really.It's not a trick of Angular, or TypeScript - it's simple JavaScript closures.

  1. function minLength(minimum) {
  2. return function(input) {
  3. return input.value.length >= minimum ? null : { minLength: true };
  4. };
  5. }

Assume you have a function which takes a "minimum" parameter and returns another function. The function defined and returned from the inside becomes the validator. The closure reference allows you to remember the value of the minimum when the validator is eventually called.

Let's apply that thinking back to a PunctuationValidator.

app/login-form.component.ts

  1. function hasPunctuation(punctuation: string, errorType: string) {
  2. return function(input: FormControl) {
  3. return input.value.indexOf(punctuation) >= 0 ?
  4. null :
  5. { [errorType]: true };
  6. };
  7. }
  8. // ...
  9. password = new FormControl('', [
  10. Validators.required,
  11. hasPunctuation('&', 'ampersandRequired')
  12. ]);

app/login-form.component.html

  1. <!-- ... -->
  2. <div [hidden]="!password.hasError('ampersandRequired')">
  3. You must have an &amp; in your password.
  4. </div>
  5. <!-- ... -->

View Example

Validating Inputs Using Other Inputs

Keep in mind what was mentioned earlier: inputs have access to their parent context via .root.Therefore, complex validation can happen by drilling through the form, via root.

  1. function duplicatePassword(input: FormControl) {
  2. if (!input.root || !input.root.controls) {
  3. return null;
  4. }
  5. const exactMatch = input.root.controls.password === input.value;
  6. return exactMatch ? null : { mismatchedPassword: true };
  7. }
  8. // ...
  9. this.duplicatePassword = new FormControl('', [
  10. Validators.required,
  11. duplicatePassword
  12. ]);

View Example

原文: https://angular-2-training-book.rangle.io/handout/forms/reactive-forms/reactive-forms_custom_validation.html