Ivti
Ivti

Reputation: 29

Implement "Confirm Password" in angular2

Bear in mind that i'am quit new to Angular2.

I'am currently working on a app and stumbled upon a little problem. I'am trying to make a "confirm password" for my registration.

I'am using MEAN with Angular2 - User Registration and Login Example & Tutorial (link)

I haven't been playing around much with the basic code. So my starting point is the same as the one you can see on the website.

What I tried doing was just copy/past the existing password (html code) and remake it into a "confirm password" (html code). So the html works as it should - you can input your password again. But there is no compare function. And I don't really know where or rather how to make on.

I've tried to find where the "password" function is, and found something that resembles it in login.component.ts and register.component.ts but I can't figure out how to achieve my goal..

Any suggestions, guides or/and tips are MUCH appreciated!

Upvotes: 1

Views: 1547

Answers (2)

Razvan Dumitru
Razvan Dumitru

Reputation: 12452

You can use the following package: https://github.com/yuyang041060120/ng2-validation

Then you have the possibility to define your password and confirm password controls:

let password = new FormControl('', Validators.required);
let certainPassword = new FormControl('', CustomValidators.notEqualTo(password));

this.form = new FormGroup({
  password: password,
  certainPassword: certainPassword
});

And to display errors if there are any:

<form [formGroup]="form">
  <input type="password" formControlName="password"/>
  <p *ngIf="form.controls.password.errors?.required">required error</p>
  <input type="password" formControlName="certainPassword"/>
  <p *ngIf="form.controls.certainPassword.errors?.notEqualTo">notEqualTo error</p>
</form>

Upvotes: 0

Tiep Phan
Tiep Phan

Reputation: 12596

you can easy archive this by using Reactive Forms and Validator in Angular, here is simple example of register component with validate same password.

note: you could learn more about Reactive Forms in this document https://angular.io/docs/ts/latest/guide/reactive-forms.html

First, we need import Reactive Forms Module to our app:

@NgModule({
  imports: [ BrowserModule, ReactiveFormsModule ], // <- this module
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

and create new Component:

@Component({
  selector: 'tpc-register',
  template: `
    <form [formGroup]="form" novalidate (ngSubmit)="onSubmit()">
      <div>
        <label>
          Username:<br>
          <input formControlName="username" type="text">
        </label>
      </div>
      <div formGroupName="passGroup">
        <label>
          Password:<br>
          <input formControlName="password" type="password"
            [class.form-error]="form.get('passGroup').errors?.invalid"
          >
        </label>
      </div>
      <div formGroupName="passGroup">
        <label>
          Confirm Password:<br>
          <input formControlName="confirmPassword" type="password"
            [class.form-error]="form.get('passGroup').errors?.invalid"
          >
        </label>
      </div>
      <button [disabled]="form.invalid">Register</button>
    </form>
    <pre>Form value: {{ form.value | json }}</pre>
    <pre>Form valid: {{ form.valid }}</pre>
  `,
  styles: [
  `
  .form-error {
    border-color: red
  }
  `  
  ]
})
export class TpcRegister implements OnInit {
  form: FormGroup;
  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    // create new Form by FormBuilder
    this.form = this.fb.group({
      username: ['', /* Validation */[Validators.required]],
      // for password and confirm password
      passGroup: this.fb.group({
        password: ['', /* Validation */[Validators.required]],
        confirmPassword: ['', /* Validation */[Validators.required]],
      }, /* Custom Validation */ {
        validator: comparePassword
      })
    })
  }

  onSubmit() {
    if (this.form.valid) {
      const formValue = Object.assign({}, this.form.value)
      formValue.password = formValue.passGroup.password
      delete formValue.passGroup

      // do stuff to register user with formValue
      console.log(formValue)
    }
  }
}

please take a look to ngOnInit method, the magic stuff happen here.

We create passGroup and apply custom validator for this group, in this case is comparePassword.

export function comparePassword(group: FormGroup) {
  const pass = group.value;
  return (pass.password === pass.confirmPassword) ? null /* It's good */ : {
    invalid: true
  }
}

the above function will take a group of type FormGroup, then we could compare values of password and confirmPassword.

if they are same, so nothing error here, we return null, otherwise we will return an object to tell our app this group has errors.

You can play with live demo here: https://plnkr.co/edit/Vk0G7DaPB1hRK9f1UVEX?p=preview

Upvotes: 3

Related Questions