我在角度2中匹配密码验证时遇到错误

时间:2017-05-19 07:15:11

标签: angular angular2-forms

我尝试过所有方法,但最后我收到了这个错误。

错误在C:/laragon/www/myapp/src/app/registration/registration.component.ts(30,9):类型'{validator:any; }' 不是一个 ssignable到'ValidatorFn'类型的参数。   对象文字只能指定已知属性,'ValidatorFn'类型中不存在'validator'。

这是我的组件代码:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, Validator, ValidatorFn } from '@angular/forms';
//import { emailValidator, matchingPasswords } from '../../app/validators/validators';

@Component({
    selector: 'app-registration',
    templateUrl: './registration.component.html',
    styleUrls: ['./registration.component.css']
})
export class RegistrationComponent implements OnInit {
    private RegistrationForm: FormGroup;
    constructor() { }

    ngOnInit() {
        this.RegistrationForm = new FormGroup({
            firstname: new FormControl(null, [
                Validators.required,
                Validators.minLength(3)
            ]),
            email: new FormControl(null, [
                Validators.required,
                Validators.pattern(/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/)
            ]),
            passwords: new FormControl(null, [
                Validators.required,
                Validators.minLength(6)
            ]),
            confirmpwd: new FormControl(null, [
                Validators.required
            ]),
        }, { validator: matchingPasswords.bind('passwords', 'confirmpwd') });

        function matchingPasswords(passwordKey: string, confirmPasswordKey: string) {
            return (group: FormGroup): { [key: string]: any } => {
                let password = group.controls[passwordKey];
                let confirmPassword = group.controls[confirmPasswordKey];

                if (password.value !== confirmPassword.value) {
                    return {
                        mismatchedPasswords: true
                    };
                }
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

看起来您的匹配密码函数未被识别为ValidatorFn,我认为它因为它有不同的参数。 ValidatorFn希望您传入一个AbstractControl。

以下是where the ValidatorFn interface is declared的链接,界面如下:

export interface ValidatorFn { (c: AbstractControl): ValidationErrors|null; }

以下是我编写验证器的示例:

matchingPasswords(c: AbstractControl): {[key: string]: any} {
  let password = c.get(['passwords']);
  let confirmPassword = c.get(['confirmpwd']);

  if (password.value !== confirmPassword.value) {
    return { mismatchedPasswords: true };
  }
  return null;
}

Angular会将formGroup传递给matchingPasswords,然后使用getter get()访问密码。

然后,您可以将其添加到表单组中,如下所示:

this.RegistrationForm = new FormGroup({
  firstname : new FormControl(null,[
    Validators.required,
    Validators.minLength(3)
  ]),
  email : new FormControl(null,[
    Validators.required,
    Validators.pattern(/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/)
  ]),
  passwords : new FormControl(null,[
    Validators.required,
    Validators.minLength(6)
  ]),
  confirmpwd : new FormControl(null,[
    Validators.required
  ]), 
}, {validator: matchingPasswords} );

顺便说一下,我喜欢将所有验证器放在可以导入我的服务的Validator类中。它可能会帮助你做同样的事情。

export class FormValidator {

  static nonEmpty(control: any) {
    if (!control.value || control.value.length === 0) {
      return { 'noElements': true };
    }
    return null;
  }


  matchingPasswords(c: AbstractControl): {[key: string]: any} {
    let password = c.get(['passwords']);
    let confirmPassword = c.get(['confirmpwd']);

    if (password.value !== confirmPassword.value) {
      return { mismatchedPasswords: true };
    }
    return null;
  }
}

然后你可以在你的表格中使用它:

{ validator: FormValidator.matchingPasswords }
祝你好运!

答案 1 :(得分:2)

这在技术上可能与此重复: Repeat password validation not working (我之前也链接过)。

但是,现在我想在尝试代码时指出一个“新发现”。无法重现您在Plunker中的确切错误,但我确实设法出错。出于某种原因,在构建表单时使用new FormGroup()时会引发错误。我知道为什么会这样,如果有人能告诉我原因,我会很高兴! :)

所以至少在使用FormBuilder时,一切似乎都很好:

constructor(private fb: FormBuilder) { } // inject formbuilder

ngOnInit() {
  this.RegistrationForm = this.fb.group({
    firstname: new FormControl(null, [
            Validators.required,
            Validators.minLength(3)
        ]),
        email: new FormControl(null, [
            Validators.required,
            Validators.pattern(/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/)
        ]),
    passwords : new FormControl(null,[
      Validators.required,
      Validators.minLength(6)
  ]),
  confirmpwd : new FormControl(null,[
    Validators.required
  ]),         
  },{validator: this.matchingPasswords}) // remember to use 'this'
}

然后是matchingPasswords - 函数,它基本上是本答案开头提到的链接中(我的)答案中提供的内容的精确副本。

matchingPasswords = (control: AbstractControl): {[key: string]: boolean} =>{

  const newPassword = control.get('passwords');
  const confirmPassword = control.get('confirmpwd');
  // if no values, valid
  if (!newPassword || !confirmPassword) {
    return null;
  } 
  // if values match return null, else 'mismatchedPasswords:true'  
  return newPassword.value === confirmPassword.value ? null : { mismatchedPasswords: true };
}    

最后是 DEMO