密码确认密码验证检查

时间:2016-09-29 22:38:27

标签: angular typescript

我正在使用Angular 2最新版本。我正在尝试检查密码字段和确认密码中的密码是否相同。或者如果两个字段匹配。这是我到目前为止所做的,但它似乎并没有起作用。

任何帮助都将不胜感激。

Signup.component.ts

import { Component, OnInit } from '@angular/core';
import {Validators, FormGroup, FormBuilder } from "@angular/forms";

@Component({
  selector: 'app-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.css']
})
export class SignupComponent implements OnInit {
  myForm: FormGroup;
  constructor(private fb: FormBuilder) {
  }
  onSignup() {
    console.log("Logged in");
  }

  ngOnInit() {
    this.myForm = this.fb.group({
      email: ['', Validators.compose([
        Validators.required,
      ])],
      password: ['', Validators.compose([
          Validators.required,
      ])],
      confirmPassword: ['', Validators.compose([
        Validators.required,

      ])],
    });
  }
}

Signup.component.html

<div class="container">
  <form [formGroup]="myForm" novalidate (ngSubmit)="onSignup()">
    <div class="form-group">
      <label for="email">Email</label>
      <input type="email" class="form-control" id="email" name="email">
      <small [hidden]="myForm.controls.email.valid || (myForm.controls.email.pristine && !myForm.submitted)" class="text-danger">
        Email is required.
      </small>
    </div>
    <div class="form-group">
      <label for="password">Password</label>
      <input type="password" class="form-control" id="password" name="password" validateEqual="confirmPassword" reverse="true">
      <small [hidden]="myForm.controls.password.valid || (myForm.controls.password.pristine && !myForm.submitted)" class="text-danger">
        Password is required
      </small>
    </div>
    <div class="form-group">
      <label for="confirmPassword">Retype password</label>
      <input type="password" class="form-control" id="confirmPassword" name="confirmPassword" validateEqual="password" reverse="false">
      <small [hidden]="myForm.controls.confirmPassword.valid || (myForm.controls.confirmPassword.pristine && !myForm.submitted)" class="text-danger">
        Password mismatch
      </small>
    </div>
    <button type="submit" [disabled]="!myForm.valid" class="btn btn-default">Submit</button>
  </form>
</div>

Validator.ts

import { Directive, forwardRef, Attribute } from '@angular/core';
import { Validator, AbstractControl, NG_VALIDATORS } from '@angular/forms';
@Directive({
    selector: 'validator',
    providers: [
        { provide: NG_VALIDATORS, useExisting: forwardRef(() => EqualValidator), multi: true }
    ]
})
export class EqualValidator implements Validator {
    constructor( @Attribute('validateEqual') public validateEqual: string,
                 @Attribute('reverse') public reverse: string) {
    }
    private get isReverse() {
        if (!this.reverse) return false;
        return this.reverse === 'true' ? true: false;
    }
    validate(c: AbstractControl): { [key: string]: any } {
        // self value
        let v = c.value;
        // control vlaue
        let e = c.root.get(this.validateEqual);
        // value not equal
        if (e && v !== e.value && !this.isReverse) {
            return {
                validateEqual: false
            }
        }

        // value equal and reverse
        if (e && v === e.value && this.isReverse) {
            delete e.errors['validateEqual'];
            if (!Object.keys(e.errors).length) e.setErrors(null);
        }
        // value not equal and reverse
        if (e && v !== e.value && this.isReverse) {
            e.setErrors({
                validateEqual: false
            })
        }
        return null;
    }
}

非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:-1)

这是一个工作插件,它连接到值更改以直接监视值并设置错误。

我确信有更多可以找到或想到的聪明解决方案。

http://plnkr.co/PXcae8kq9quYFQC2x7K2

 subscribeToFormChangesAndSetValidity() {
      const myFormValueChanges$ = this.myForm.controls["passwords"].valueChanges;

      myFormValueChanges$.subscribe(x => {
          if(x.password === x.confirmPassword) {
              this.myForm.controls["passwords"].setErrors(null);
          } else {
              this.myForm.controls["passwords"].setErrors({ "notValid" : true});
          }
      });
  }

  ngOnInit() {
    this.myForm = this.fb.group({
      email: ['', Validators.required],
      passwords: this.fb.group({
        password: ['', Validators.required],
        confirmPassword: ['', Validators.required]
        })
        });

        this.subscribeToFormChangesAndSetValidity();
  }