-2

I'm trying to create Angular 5 registration form with .NET Core.

I'm checking whether password and retyped password are the same in the registration form. I'm using FormBuilder for form.

But checking password1 and password2 is always failing. I have tried === also.

if (this.RegistrationForm.valid) {
  if (this.RegistrationForm.get('password1') == this.RegistrationForm.get('password2')) {
    this.MyService.Register(this.RegistrationForm.value).subscribe((data) => {}, error => this.errorMessage = error)
  } else {
    this.errorMessage = "cdscs";
  }
}

constructor(private fb: FormBuilder, private MyService: RoadSignService) {
        this.RegistrationForm = this.fb.group({
            Id: 0,
            name: ['', [Validators.required]],
            email: ['', [Validators.required]],
            gender: ['', [Validators.required]],
            department: ['', [Validators.required]],
            address: ['', [Validators.required]],
            password1: ['', [Validators.required]],
            password2: ['', [Validators.required]]
        })
    }

Image

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

4 Answers4

0

I would approach this as a validator across the entire FormGroup, rather than submit the form, then do the check.

When you define the FormGroup, you can add a validator for the entire group, giving you access to all of the controls/values as such:

validatePasswords(formGroup: FormGroup): any {
    const password = formGroup.controls['password'];
    const confirmPassword = formGroup.controls['confirmPassword'];

    // don't validate
    if (password.pristine || confirmPassword.pristine) {
      return null;
    }

    formGroup.markAsTouched();

    if (password.value === confirmPassword.value) {
      return null;
    }

    return confirmPassword.setErrors({
      notEqual: true
    });
  }

form = this.formBuilder.group({
  . . .,
  password: [
    '', [
      Validators.required,
      Validators.pattern(regexPatterns.password),
    ]
  ],
  confirmPassword: [
    '', [
      Validators.required,
      Validators.pattern(regexPatterns.password)
    ]
  ]
}, {
  validator: this.validatePasswords
});

In this example, regexPatterns.password is just a shared import of RegExp objects, and the expression is: /^(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&+=*]).*/

Now you can show the user if the two fields match before you submit the form and invoke any other logic, API calls or any expensive operations.

Brandon Taylor
  • 33,823
  • 15
  • 104
  • 144
0

I guess the best approach here would be adding a custom validator to compare both passwords, e.g:

// Custom validator
function validateRePassword(control: FormControl){
  const { root } = control;
  const pass = root.get('password'),
        rePass = root.get('rePassword');

  if(!pass || !rePass) {
    return null;
  }

  const passVal = pass.value,
        rePassVal = rePass.value;

  const result = passVal===rePassVal ? null : { passDontMatch: true };
  return result;
}

// Form initialization
this.formGroup = fb.group({
      user: fb.control('UserName'),
      password: fb.control(''),
      rePassword: fb.control('', [validateRePassword])
    })

// function to check if the control has the 'passDontMatch' error and therefore display some related message
passMatch(){
    return !this.formGroup.get('rePassword').hasError('passDontMatch');
  }
Dan R.
  • 638
  • 5
  • 13
0

Custom validator didn't work for me, even with a custom state matcher.

I'm checking password with hand.

<input type="password" formControlName="password" (input)="checkPasswordsMatch()">
<input type="password" formControlName="confirmPassword" (input)="checkPasswordsMatch()">
<p class="error" *ngIf="form.get('confirmPassword').hasError('notSame')"> It works </p>
checkPasswordsMatch(): void {
  const password = this.form.get('password');
  const confirmPassword = this.form.get('confirmPassword');

  if (password.value !== confirmPassword.value) {
    this.form.get('confirmPassword').setErrors({ notSame: true });
  }
}


Pierre D
  • 327
  • 1
  • 2
  • 7
-1

Once your user submits the form, the form value will be available as a JSON Object in this.RegistrationForm.value. So you can use that to make the comparison.

Just use this.RegistrationForm.value.password1 === this.RegistrationForm.value.password2

if (this.RegistrationForm.valid) {
  if (this.RegistrationForm..value.password1 === this.RegistrationForm.value.password2) {
    this.MyService.Register(this.RegistrationForm.value)
      .subscribe(
        (data) => {}, 
        error => this.errorMessage = error
      )
  } else {
    this.errorMessage = "cdscs";
  }
}

PS: If you want to create a Custom Validator that does this, please refer to this OP.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110