Angular validate password field with Formgroup

Asked

Viewed 1,154 times

0

I have the following code:

TS code:

...
onRegisterForm: FormGroup;
ngOnInit() {

    this.onRegisterForm = this._fb.group({
      nome: ['', Validators.compose([
        Validators.required
      ])],      
      email: ['', Validators.compose([
        Validators.required
      ])],
      senha: ['', Validators.compose([
        Validators.required,
        Validators.minLength(6)
      ])],
      confirm_senha: ['', Validators.compose([
        Validators.required
      ])]
    });
  }
...

HMTL:

<ion-item>
        <ion-label floating>Senha</ion-label>
        <ion-input type="{{isPassword ? 'password' : 'text' }}" [(ngModel)]="userData.senha" formControlName="senha" minlength="6"></ion-input>
        <button ion-button clear color="dark" type="button" class="btn-icon-eye" item-right (click)="showPassword()">
          <ion-icon name="ios-eye-outline" class="icon-eye" item-right></ion-icon>
        </button>
      </ion-item>
      <p ion-text color="danger" class="has-error" *ngIf="onRegisterForm.get('senha').touched && onRegisterForm.get('senha').hasError('required')">Este campo é obrigatório.</p>
      <p ion-text color="danger" class="has-error" *ngIf="onRegisterForm.get('senha').hasError('minLength')">A senha deve conter no mínimo 6 caracteres.</p>

The two validators work perfectly (the problem is in the display of the messages).

When I click on the field and exit without filling it out, the message is displayed: "This field is required.". However, when I type less than six characters in the message: "The password must contain at least 6 characters." is not displayed!

Parsing the code fails to find the error!

1 answer

2


Some time ago I discovered the problem and forgot to post the answer.

The mistake was in:

onRegisterForm.get('senha').hasError('minLength')

Where minLength should be in minuscule minlength

In this way:

onRegisterForm.get('senha').hasError('minlength')
  • How did you do to validate password check and confirm password?

  • In HTML "<p ion-text color="Danger" class="has-error" *ngIf="onRegisterForm.get('confirm_password'). Touched && (onRegisterForm.get('confirm_password').hasError('minlength') || confirm_password != userdata.password)">Incorrect confirmation password. </p>" and on the TS inside the registration function "if ( this.userData.password != this.confirm_password ) Return false;".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.