Password and confirm password validation


#1

Hi all,
can some one help me for the below.
Ionic 2 version is : 2.0.0-rc.1

import { Component } from '@angular/core';
//import {DataServices} from '../../providers/dataservices';
import { NavController } from 'ionic-angular';
import {FormGroup, FormBuilder, Validators} from '@angular/forms';

@Component({
  selector: 'page-signup',
  templateUrl: 'signup.html',
})
export class SignupPage {

  formdata = {
    p_surname: '',
    p_person_id: '',
    p_email: '',
    p_password: '',
    p_confirm_password: ''
  };
  submitAttempt: boolean = false;
  myForm: FormGroup;

  constructor(public nav: NavController
    , public formBuilder: FormBuilder
  ) {
    this.myForm = this.formBuilder.group({
      p_surname: ['', Validators.compose([Validators.maxLength(30),Validators.required])],
      p_person_id: ['', Validators.compose([Validators.maxLength(10), Validators.required])],
      p_email: ['', Validators.compose([Validators.required])],
      //password_ctrl: this.formBuilder.group({
        p_password: ['', Validators.compose([Validators.required])],
        p_confirm_password: ['', Validators.compose([Validators.required])]
      //}, this.matchPassword)
    }, {'validator': this.isMatching});

  }

  ionViewDidEnter(){

  }

  isMatching(group: FormGroup){

    console.log("password check");

    var firstPassword = group.controls['p_password'].value;
    var secondPassword = group.controls['p_confirm_password'].value;
    if((firstPassword && secondPassword) && (firstPassword != secondPassword)){
      console.log("mismatch");
      return { "pw_mismatch": true };
    } else{
      return null;
    }

  }

  matchPassword(group): any {
    let password = group.controls.p_password;
    let confirm = group.controls.p_confirm_password;
console.log("indise");
    // Don't kick in until user touches both fields
    if (password.pristine || confirm.pristine) {
      console.log("sd");
      return null;
    }

    // Mark group as touched so we can add invalid class easily
    group.markAsTouched();

    if (password.value === confirm.value) {
      return null;
    }
console.log("sdfdsf");
    return {
      isValid: false
    };
  }

  register(){


    this.submitAttempt = true;


    if(!this.myForm.valid){
      console.log("Not valid!");
    }
    else {
      console.log("success!");
      console.log(this.myForm.value);
      console.log(this.formdata);
    }

  }

}

and template is below

<ion-header>

  <ion-navbar secondary>
    <ion-title>Create Account</ion-title>
  </ion-navbar>

</ion-header>


<ion-content>

  <ion-card>
    <ion-card-header>
      <ion-row>
        <ion-col>
          <h2>Personal Details</h2>
        </ion-col>
      </ion-row>
    </ion-card-header>
    <ion-card-content>
      <form [formGroup]="myForm">
        <ion-row>
          <ion-col>
            <ion-list inset>

              <ion-item>
                <ion-label>
                  <ion-icon name="person"></ion-icon>
                </ion-label>
                <ion-input placeholder="Surname" type="text" [(ngModel)]="formdata.p_surname" name="p_surname" formControlName="p_surname"></ion-input>
              </ion-item>

              <ion-item *ngIf="!myForm.controls.p_surname.valid  && (submitAttempt)">
                <p>Please enter a valid Surname.</p>
              </ion-item>

              <ion-item>
                <ion-label>
                  <ion-icon name="person"></ion-icon>
                </ion-label>
                <ion-input placeholder="Membership No" type="text" [(ngModel)]="formdata.p_person_id" name="p_person_id" formControlName="p_person_id"></ion-input>
              </ion-item>

              <ion-item *ngIf="!myForm.controls.p_person_id.valid  && (submitAttempt)">
                <p>Please enter a valid Membership no.</p>
              </ion-item>

              <ion-item>
                <ion-label>
                  <ion-icon name="mail"></ion-icon>
                </ion-label>
                <ion-input placeholder="Email" type="email" [(ngModel)]="formdata.p_email" name="p_email" formControlName="p_email"></ion-input>
              </ion-item>

              <ion-item *ngIf="!myForm.controls.p_email.valid  && (submitAttempt)">
                <p>Please enter a valid Email address.</p>
              </ion-item>

                <ion-item>
                  <ion-label>
                    <ion-icon name="lock"></ion-icon>
                  </ion-label>
                  <ion-input placeholder="Password" type="password" [(ngModel)]="formdata.p_password" name="p_password" formControlName="p_password"></ion-input>
                </ion-item>


                <ion-item>
                  <ion-label>
                    <ion-icon name="lock"></ion-icon>
                  </ion-label>
                  <ion-input placeholder="Confirm password" type="password" [(ngModel)]="formdata.p_confirm_password" name="p_confirm_password" formControlName="p_confirm_password"></ion-input>
                </ion-item>

<!--
                <ion-item *ngIf="!myForm.controls.password_ctrl.valid  && (submitAttempt)">
                  <p>Please enter a valid password.</p>
                </ion-item>
              </div>
-->

<!--
              <ion-item *ngIf="!myForm.controls.p_confirm_password.valid  && (submitAttempt)">
                <p>Please enter a valid Confirm Password.</p>
              </ion-item>
-->
            </ion-list>

            <button ion-button color="primary"(click)="register()" full>Register</button>
          </ion-col>
        </ion-row>
       </form>
    </ion-card-content>
  </ion-card>
</ion-content>

Can anyone let me know how to show the validation error that is thrown by isMatching validator, or is there any other method better than this?


#2

Can anyone light on it?


#3

Did you get it working?


#5

I don’t think there is any need for Promises here. You can just do this.


#6

Use validator for confirm password like this
It works

import { FormControl } from ‘@angular/forms’;
import { ValidationResult } from ‘…/shared/interfaces’;

export class ConfirmPasswordValidator {
static checkConfirmPassword(control: FormControl): ValidationResult {

    if (control.value == control.root.value['password']) {
        console.log('passwords  match');
        return null;
    } else {
        return { isValid: true };
    }

}
}


#7

…and now it’s going to look like I am either replying to air or have a time machine. I still don’t see any need for making a Promise here.


#8

one good example is here: https://angular-2-training-book.rangle.io/handout/forms/reactive-forms/reactive-forms_custom_validation.html and see live demo example


#9

I managed to do that, you can use the following module:

Or write your own:

Here is my code:
inside my constructor:

this.userForm = formBuilder.group({
      firstName: ['', Validators.required],
      lastName: ['', Validators.required],
      email: ['', Validators.compose([Validators.required, SignUpPageComponent.emailValidator])],
      password: ['', Validators.compose([Validators.required, Validators.minLength(6), Validators.maxLength(12), Validators.pattern('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{6,12}$')])],
      confirmPassword: ['', Validators.required],
    }, {validator: this.matchingPasswords('password', 'confirmPassword')}); 


matchingPasswords(passwordKey: string, confirmPasswordKey: string) {
    // TODO maybe use this https://github.com/yuyang041060120/ng2-validation#notequalto-1
    return (group: FormGroup): {[key: string]: any} => {
      let password = group.controls[passwordKey];
      let confirmPassword = group.controls[confirmPasswordKey];

      if (password.value !== confirmPassword.value) {
        return {
          mismatchedPasswords: true
        };
      }
    }
  }

Inside the template:

      <ion-item class='form-text error' *ngIf="userForm.controls.password.touched && !userForm.controls.password.valid">
        <ion-label no-margin stacked wrap-text>Password must be between 6 and 12 characters with at least one capital letter, one small letter, and one digit.</ion-label>
      </ion-item>
      <ion-item>
        <ion-label stacked>Re-enter Password</ion-label>
        <ion-input type="password" [(ngModel)]="confirmPassword" formControlName="confirmPassword"
                   required show-password></ion-input>
      </ion-item>
      <ion-item class='form-text error' *ngIf="userForm.controls.confirmPassword.touched && userForm.hasError('mismatchedPasswords') && userForm.controls.password.valid">
        <ion-label no-margin stacked>Passwords do not match</ion-label>
      </ion-item>

#10

Check this link i find my answer this link.

Password Validation Ionic 2


#11

Gracias tu codigo es el mejor.


#12

This worked for me too. Thank you so much


#13

register.ts

/* validate */

ngOnInit() {
let EMAILPATTERN = /^[a-z0-9!#$%&’+/=?^_`{|}~.-]+@a-z0-9?(.a-z0-9?)$/i;
this.signupform = new FormGroup({
// course: new FormControl(’’, [Validators.required]),
dob: new FormControl(’’, [Validators.required]),
gender: new FormControl(’’, [Validators.required]),
number: new FormControl(’’, [Validators.required, Validators.minLength(10)]),
name: new FormControl(’’, [Validators.required, Validators.pattern(’[a-zA-Z ]’), Validators.minLength(4), Validators.maxLength(30)]),
// fname: new FormControl(’’, [Validators.required, Validators.pattern(’[a-zA-Z ]
’), Validators.minLength(4), Validators.maxLength(30)]),
email: new FormControl(’’, [Validators.required, Validators.pattern(EMAILPATTERN)]),
city: new FormControl(’’, [Validators.required]),
password: new FormControl(’’, [Validators.required]),
re_password: new FormControl(’’, [Validators.required,this.equalto(‘password’)])
});
}

equalto(field_name): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => {

let input = control.value;

let isValid=control.root.value[field_name]==input
if(!isValid)
return { ‘equalTo’: {isValid} }
else
return null;
};
}

register.html

Password
          </ion-item>
          
          <ion-item no-lines *ngIf="( signupform.get('password').hasError('required') ) && signupform.get('password').touched">
          
          <div class="error" *ngIf="signupform.get('password').hasError('required') && signupform.get('password').touched">
          Password is required
          </div>
          
          </ion-item>
          
          
          <ion-item>
          <ion-label floating>Confirm Password</ion-label>
          <ion-input type="password" [(ngModel)]="regData.confirm_password" formControlName="re_password"></ion-input>
          
          </ion-item>
          
          <ion-item no-lines *ngIf="( signupform.get('re_password').hasError('equalTo') || signupform.get('re_password').hasError('required') ) && signupform.get('re_password').touched">
          
          <div class="error" *ngIf="signupform.get('re_password').hasError('required') && signupform.get('re_password').touched">
          Confirm password is required
          </div>
          <div class="error" *ngIf="signupform.get('re_password').hasError('equalTo') && signupform.get('re_password').touched">
          Password Mismatch
          </div>
        </ion-item>              
    </ion-list>
    <button ion-button icon-start block round type="button" color="dark" tappable  
        [disabled]="signupform.invalid" >
      <!-- <ion-icon name="log-in"></ion-icon> -->
      Create Account
    </button>