标志性表单验证-自定义错误消息未显示

时间:2018-07-11 18:04:31

标签: html angular typescript

我已经创建了一个自定义验证程序,用于检查密码和确认密码是否相等,并且可以按预期工作,但是如果它们不匹配,它不会打印分配给它的错误消息。

路径:应用程序/验证程序-> password.validator.ts:

import { FormControl, FormGroup, NgForm, FormGroupDirective } from '@angular/forms';

export class PasswordValidator {

    static equalPasswords(fg: FormGroup) {
        let password = fg.get('password').value;
        let confirm_password = fg.get('confirm_password').value;
        if (password !== confirm_password) {
            return {
                areEqual: true
            };
        } else {
            return null;
        }
    }
}

路径:应用程序/用户/注册-> sign-up.component.ts:

import { PasswordValidator } from '../../validators/password.validator';
import { Component, OnInit } from '@angular/core';
import { NgForm, FormBuilder, Validators, FormsModule } from '@angular/forms';
import { FormGroup, FormControl, FormGroupDirective } from '@angular/forms';

export class SignUpComponent implements OnInit {

  userDetailsForm: FormGroup;
  matching_passwords_group: FormGroup;

  validation_messages = {
    'password': [
      { type: 'required', message: 'Password is required' }
    ],
    'confirm_password': [
      { type: 'required', message: 'Confirmation password is required' },
      { type: 'areEqual', message: 'Password mismatch' }
    ]
  }


  ngOnInit() {
    this.createForm();
  }

  createForm() {
    this.matching_passwords_group = new FormGroup({
      password: new FormControl('', [Validators.required]),
      confirm_password: new FormControl('', [Validators.required])
    }, (formGroup: FormGroup) => {
      console.log(PasswordValidator.equalPasswords(formGroup));
      return PasswordValidator.equalPasswords(formGroup);
    });

    this.userDetailsForm = this.fb.group({
      matching_passwords: this.matching_passwords_group});
  }

路径:app / user / sign-up-> sign-up.component.html:

<div class="row" formGroupName="matching_passwords">
    <mat-form-field class="full-width">
      <input type="password" matInput placeholder="Password" formControlName="password" required>
      <mat-error *ngFor="let validation of validation_messages.password">
        <mat-error *ngIf="userDetailsForm.get('matching_passwords').get('password').hasError(validation.type)">
          {{validation.message}}
        </mat-error>
      </mat-error>
    </mat-form-field>
    <mat-form-field class="full-width">
      <input type="password" matInput placeholder="Confirm Password" formControlName="confirm_password" required>
      <mat-error *ngFor="let validation of validation_messages.confirm_password">
        <mat-error *ngIf="userDetailsForm.get('matching_passwords').get('confirm_password').hasError(validation.type)">
          {{validation.message}}
        </mat-error>
      </mat-error>
    </mat-form-field>
  </div>

注意:     console.log(PasswordValidator.equalPasswords(formGroup));

如果密码不相等,

打印{areEqual:true}。

任何提示都值得赞赏。 谢谢!

0 个答案:

没有答案