密码并以角度确认密码验证

时间:2019-04-10 10:23:09

标签: angular typescript

我试图在一个角度项目中实施密码并确认密码验证。我关注了这篇帖子Confirm password validation in Angular 6上的答案。 但是,我无法收到任何错误消息。我不知道我在做什么错。 这是我的ts代码:

  constructor(private formBuilder:FormBuilder,private userService:UsersService,private router:Router) { }
  addForm: FormGroup;
  selected = 'option2';
  passwordsMatcher = new RepeatPasswordEStateMatcher;

  ngOnInit() {

    this.addForm = this.formBuilder.group({
      id: [],
      userName: ['', Validators.required],
      password:new FormControl( '',[ Validators.required]),
      passwordAgain: new FormControl('',[ Validators.required]),
      userRole:['',Validators.required],

    },{ validator: RepeatPasswordValidator });
  }
  onSubmit() {
    if (this.addForm.valid)
    {
    this.userService.createUser(this.addForm.value)
      .subscribe( data => {
        this.router.navigate(['newuser']);
      });
    console.log(this.addForm.controls.password.value);
  }
}
  changeClient(value) {
    console.log(value);
    console.log(this.addForm.controls.value);
}

这是我的验证者代码:

export class RepeatPasswordEStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    return (control && control.parent.get('password').value !== control.parent.get('passwordAgain').value)
  }
}
export function RepeatPasswordValidator(group: FormGroup) {
  let password = group.controls.password.value;
  let passwordConfirmation = group.controls.passwordAgain.value;

  return password === passwordConfirmation ? null: { passwordsNotEqual: true }     
}

下面是我的模板:

<div  style="height: 100vh" fxLayout="column" fxLayoutAlign="center center" >
    <h2 class="text-center">Add User</h2>
    <mat-card>
        <mat-card-content>

    <form [formGroup]="addForm" class="login-form" (ngSubmit)="onSubmit()">
    <div class="form-group">
        <mat-form-field class="example-full-width">

      <input matInput type="text" formControlName="userName" placeholder="userName" name="userName" class="form-control" id="userName">
        </mat-form-field>
    </div>

    <div class="form-group">
        <mat-form-field class="example-full-width">

      <input matInput type="password" formControlName="password" placeholder="Password" name="password" class="form-control" id="password">
      <mat-error *ngIf="addForm.controls.password.hasError('required')" >Passwords can't be empty</mat-error>
    </mat-form-field>
    </div>
    <div class="form-field">
        <mat-form-field>
        <input matInput formControlName="passwordAgain" placeholder="Confirm the password" type="password" [errorStateMatcher]="passwordsMatcher">
        <mat-error *ngIf="addForm.controls.passwordAgain.hasError('passwordsNotEqual')" >Passwords are different. They should be equal!</mat-error>
        </mat-form-field>
    </div>
    <mat-form-field>
        <mat-select placeholder="Roles" formControlName="userRole" id="userRole" (selectionChange)="changeClient($event.value)" [(value)]="selected">
          <mat-option value="Admin">Admin</mat-option>


        </mat-select>
      </mat-form-field>

      <div class="container" style="margin: 12px" fxLayout="row" fxLayoutAlign="center center">


    <button mat-raised-button color="primary">Create</button>
      </div>
  </form>
  </mat-card-content>
    </mat-card>
</div>

请帮助。谢谢。

1 个答案:

答案 0 :(得分:0)

您正在检查password中已经完成的passwordAgain中两个字段matchervalidator的相等性,

matcher的工作是检查是否应显示错误消息,在您的情况下,当addForm具有passwordsNotEqual时应显示错误消息。

由于验证器应用于FormGroup而不是FormControl上,因此在匹配器中,您必须检查FormGroup的有效性。

所以我建议修改这样的isErrorState方法:

isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    return !!(control && control.parent && control.parent.invalid && control.parent.dirty);
}

在HTML中,您应该检查formGroup错误而不是formControl。(因为验证器再次应用于addForm而不是passwordAgain

    <mat-error *ngIf="addForm.hasError('passwordsNotEqual')" >Passwords are different. They should be equal!</mat-error>
    <!-- instead of addForm.controls.passwordAgain.hasError('passwordsNotEqual') --> 

这肯定会为您工作。