Реактивная форма Подтвердите пароль и Подтвердите Email Validator angular 4 - PullRequest
0 голосов
/ 27 сентября 2018

Мне нужно проверить, имеют ли поля пароля и подтверждения одинаковые значения, используя реактивную форму угла 4+.Я видел много ответов на одно и то же здесь: форма Angular 4 проверяет повторный пароль, сравнивает поля в валидаторе с angular 4, но ни один из них мне не подходит.

Возникла проблема, как объединить подтверждение Emailи подтвердите валидатор пароля при реактивном подходе.

Работает нормально, либо подтвердите электронную почту, либо подтвердите пароль.

   this.addEmpForm = new FormGroup({
      'name': new FormControl(null, Validators.required),
      'email': new FormControl(null, [Validators.required, Validators.email]),
      'cemail': new FormControl(null, [Validators.required, Validators.email]),
      'password': new FormControl(null, Validators.required),
      'cpassword': new FormControl(null, Validators.required)
    }, this.pwdMatchValidator);
  }

  emailMatchValidator(frm: FormGroup) {
    return frm.get('password').value === frm.get('cpassword').value
      ? null : { 'mismatch': true };
  }

  pwdMatchValidator(frm: FormGroup) {
    return frm.get('password').value === frm.get('cpassword').value
      ? null : { 'mismatch': true };
  }

HTML

<span class="help-block" 
              *ngIf="addEmpForm.get('cemail').touched && cemail?.errors || 
              addEmpForm.get('cemail').touched && addEmpForm.errors?.mismatch">
                Email doesn't match
              </span> 

1 Ответ

0 голосов
/ 27 сентября 2018

Компонент TS

password: [
        '',
        [Validators.required, Validators.maxLength(50)]
    ],
    confirmPassword: [
        '',
        [
            Validators.required,
            PasswordValidator('password'),
            Validators.maxLength(50)
        ]
    ],
    emailAddress: [
        '',
        [Validators.required, Validators.email, Validators.maxLength(50)]
    ],
    confirmEmailAddress: [
        '',
        [
            Validators.required,
            Validators.email,
            EmailValidator('emailAddress'),
            Validators.maxLength(50)
        ]
    ]

VALIDATOR электронной почты

import { FormControl } from '@angular/forms';

export function EmailValidator(confirmEmailInput: string) {
  let confirmEmailControl: FormControl;
  let emailControl: FormControl;

  return (control: FormControl) => {
    if (!control.parent) {
      return null;
    }

    if (!confirmEmailControl) {
      confirmEmailControl = control;
      emailControl = control.parent.get(confirmEmailInput) as FormControl;
      emailControl.valueChanges.subscribe(() => {
        confirmEmailControl.updateValueAndValidity();
      });
    }

    if (
      emailControl.value.toLocaleLowerCase() !==
      confirmEmailControl.value.toLocaleLowerCase()
    ) {
      return {
        notMatch: true
      };
    }
    return null;
  };
}

VALIDATOR ПАРОЛЯ

import { FormControl } from '@angular/forms';

export function PasswordValidator(confirmPasswordInput: string) {
  let confirmPasswordControl: FormControl;
  let passwordControl: FormControl;

  return (control: FormControl) => {
    if (!control.parent) {
      return null;
    }

    if (!confirmPasswordControl) {
      confirmPasswordControl = control;
      passwordControl = control.parent.get(confirmPasswordInput) as FormControl;
      passwordControl.valueChanges.subscribe(() => {
        confirmPasswordControl.updateValueAndValidity();
      });
    }

    if (
      passwordControl.value !==
      confirmPasswordControl.value
    ) {
      return {
        notMatch: true
      };
    }
    return null;
  };
}

Вам нужно будет импортировать ваш валидатор в ваш файл component.ts

...