Validate with Angular 2 input are equal

0

Sorry if it is something easy, but I'm doing my pinnings in Angular 5 but I have the following question.

I would like to validate a FormGroup, I know there are approximations when creating forms, by template and by data, I am currently using the data approach, I have the following scheme .. I have an object:

registro: Object = {
nombre: null,
apellidoPaterno: null,
apellidoMaterno: null,
rfc: null,
curp: null,
telefono: null,
email: null,
passwords: {
  password1: "",
  confirmPassword: ""
}
};

I make a statement:

forma: FormGroup;

and in the constructor I declare:

this.forma = new FormGroup(
  {
    'nombre': new FormControl('', [Validators.required]),
    'apellidoPaterno': new FormControl('', [Validators.required]),
    'apellidoMaterno': new FormControl('', [Validators.required]),
    'rfc': new FormControl('', [Validators.required]),
    'curp': new FormControl('', [Validators.required]),
    'telefono': new FormControl('', [Validators.required]),
    'email': new FormControl('', [Validators.required, Validators.email]),
    'passwords': new FormGroup({
      'password': new FormControl(''),
      'confirmPassword': new FormControl('')
    }, [Validators.required]

    )
  });

and my html:

<div class="col-md-12">
<form [formGroup]="forma" (ngSubmit)="guardar()" novalidate>

<div class="form-group row">
  <label class="col-sm-2 col-form-label">Nombre:</label>
  <div class="col-sm-10">
    <input type="text" class="form-control" placeholder="Ingrese su nombre completo" formControlName="nombre" [ngClass]="{ 'is-invalid': !forma.controls['nombre'].valid  && forma.controls['nombre'].touched  }">
    <div *ngIf=" forma.controls['nombre'].touched  && !forma.controls['nombre'].valid" class="invalid-feedback">
      Es importante conocer su nombre
    </div>
  </div>
</div>
...
<div >
  <div class="form-group row" formControlName="password">
    <label class="col-sm-2 col-form-label">Contraseña:</label>
    <div class="col-sm-10" formGroupName="passwords">
      <input type="password" class="form-control" placeholder="Ingrese su nombre completo" >
      {{forma.get('passwords.password').valid}}
      <div *ngIf="forma.controls['passwords'].controls['confirmPassword'].invalid">
        Invalido
      </div>
    </div>
  </div>

  <div class="form-group row">
    <label class="col-sm-2 col-form-label">Repita su contraseña:</label>
    <div class="col-sm-10" formGroupName="passwords">
      <input type="password" class="form-control" placeholder="Ingrese su nombre completo">
      {{forma.get('passwords.confirmPassword').valid}}
      <div *ngIf="forma.controls['passwords'].controls['password'].invalid">
        Invalido
      </div>
    </div>
  </div>
</div>

<button type="submit" class="btn btn-outline-primary btn-block">Guardar</button>

The fact is that the control is validated when the focus is lost. If you apply this sequence of actions it does not work for me:

1) you enter password. It will give you an error in password when losing focus because it is different than confirmPassword (which is empty)

2) you enter as confirmPassword the same one you entered as password. When losing focus confirmPassword will be valid but password is still invalid because its validator is not running.

I would like to validate in real time that the 2 inputs are valid and show the error in the input confirmPassword

    
asked by Jose Antonio Pino 15.05.2018 в 20:44
source

1 answer

0

Code

    private forma: FormGroup;
    /**
    * @summary Metodo constructor del componente (inyección de dependencias)
    * @param _form Manejar formularios reactivos
    */
    constructor(private _formBuilder: FormBuilder) { }
    /**
    * @summary Ejecutado seguido del método contructor
    */
    ngOnInit() {
        this.initForm();
    }
    /**
    * @summary Crea nuestro formulario
    */
    private initForm = (): void {
        this.forma = this._formBuilder.group({
          password: ['', [Validators.required]],
          confirmPassword: ['', [Validators.required]],
        });
    }

    /**
     * @summary Valida si las contraseñas coinciden
     * @param _form FormGroup => formulario
     * @return boolean
     */
    private passwordsMatch = (_form: FormGroup): boolean => {
      if (_form.controls['password'].touched && _form.controls['confirmPassword'].touched) {
          if (_form.value.password === _form.value.confirmPassword) {
              return true;
          } else {
              return false;
          }
      }
      return true;
  }

  /**
   * @summary Vefifica las contraseñas que sean validas y coincidan
   * @param _field FormControlName a validar
   * @param _form FormGroup => formulario
   * @return Object json: aplica o no la clase  "is-invalid" borde del input en rojo
   */
  private verifyPasswords = (_field: string, _form: FormGroup): any => {
      let result = false;
      if (!this.passwordsMatch(_form) || !this.isFieldValid(_field, _form)) {
          result = true;
      }
      return { 'is-invalid': result };
  }

  /**
   * @summary Usada para cuando un campo no cumple una validación y  mostrar el mensaje
   * @param _field FormControlName ==> campo a validar
   * @param _form FormGroup ==> Formulario al que pertenece el campo a validar
   * @return boolean
   */
  public isFieldValid(_field: string, _form: FormGroup): boolean {
      let valid = true;
      if (_form.get(_field).invalid && _form.get(_field).touched) {
          valid = false;
      }
      return valid;
  }

In the view

<div class="col-md-12">
    <form [formGroup]="forma" (ngSubmit)="guardar()" novalidate>
        <div class="form-group row">
            <label class="col-sm-2 col-form-label">Contraseña:</label>
            <div class="col-sm-10">
                <input type="password" class="form-control" formControlName="password" [ngClass]="verifyPasswords('password', forma)">
                <div *ngIf="!isFieldValid('password', forma)" class="invalid-feedback">
                    Inválido
                </div>
            </div>
        </div>
        <div class="form-group row">
            <label class="col-sm-2 col-form-label">Repita su contraseña:</label>
            <div class="col-sm-10">
                <input type="password" class="form-control m-input" formControlName="confirmPassword" [ngClass]="verifyPasswords('confirmPassword', forma)">
                <div *ngIf="!isFieldValid('confirmPassword', forma)" class="invalid-feedback">
                    Inválido
                </div>
                <div *ngIf="!passwordsMatch(forma)" class="invalid-feedback">
                    Las contraseñas no coinciden.
                </div>
            </div>
        </div>
    </form>
</div>
    
answered by 18.05.2018 в 06:00