Facebook
From Adam Krupa, 4 Years ago, written in TypoScript.
Embed
Download Paste or View Raw
Hits: 201
  1. export const FieldMatchValidator = (errorName: string = 'notMatched') => {
  2.   return (...formControlNames: string[]): ValidatorFn => {
  3.     return (group: FormGroup): { [key: string]: any } => {
  4.  
  5.       const controls: AbstractControl[] = formControlNames.map(name => {
  6.         return group.controls[name];
  7.       });
  8.  
  9.       const areMatched = controls.every((control, index, array) => {
  10.         if (!control) {
  11.           throw new Error('Control not exist or given bad name!');
  12.         }
  13.         return array[0].value === control.value;
  14.       });
  15.  
  16.       if (!areMatched) {
  17.         controls.forEach(control => {
  18.           const controlErrors = control.errors || {};
  19.           controlErrors[errorName] = true;
  20.           control.setErrors(controlErrors);
  21.           control.markAsTouched();
  22.         });
  23.         return { [errorName]: true };
  24.       }
  25.  
  26.       controls.forEach(control => {
  27.         const controlErrors = control.errors || {};
  28.         delete controlErrors[errorName];
  29.         if (Object.keys(controlErrors).length === 0) {
  30.           control.setErrors(null);
  31.         }
  32.       });
  33.  
  34.       return null;
  35.     };
  36.   };
  37. };
  38.  
  39.  
  40. // in component (.ts)
  41.  
  42. this.form = this.formBuilder.group({
  43.       usernameInput: ['', Validators.required],
  44.       emailInput: ['', [Validators.required, Validators.email]],
  45.       phoneInput: ['', Validators.required],
  46.       confirmPhoneInput: ['', Validators.required],
  47.       passwordInput: ['', [Validators.required]],
  48.       confirmPasswordInput: ['', [Validators.required]]
  49. }, { validators: [
  50.       FieldMatchValidator('notMatchedPasswords')('passwordInput', 'confirmPasswordInput'),
  51.       FieldMatchValidator('notMatchedPhones')('phoneInput', 'confirmPhoneInput')
  52. ] });
  53.  
  54.  
  55. // in component (.html)
  56.  
  57. *ngIf="form.hasError('notMatchedPasswords')" or
  58. *ngIf="form.controls['passwordInput'].hasError('notMatchedPasswords')"