Angular 2中的自定义重复密码验证错误

时间:2017-10-31 06:13:05

标签: angular typescript angular-validation

我正在从参考scotch.io网站学习注册表格的重复密码的Angular2自定义验证:
https://scotch.io/@ibrahimalsurkhi/match-password-validation-with-angular-2

这是我的validator.compare.ts代码:

import {AbstractControl} from '@angular/forms';
export class PasswordValidation {

    static MatchPassword(AC: AbstractControl) {
       let password = AC.get('password').value; // to get value in input tag
       let confirmPassword = AC.get('confirmPassword').value; // to get value in input tag
        if(password != confirmPassword) {
            console.log('false');
            AC.get('confirmPassword').setErrors( {MatchPassword: true} )
        } else {
            console.log('true');
            return null
        }
    }
}

和Registration.ts:

import { OnInit, Component } from "@angular/core";
import { UserModel } from "../../_model/usermodel";
import { FormGroup, FormControl, Validators } from "@angular/forms";
import { PasswordValidation } from '../../_utilities/_validations/validator.compare';

@Component({
    templateUrl: './_componant/registration/registration.html'
})

export class RegistrationComponent implements OnInit {
    user: UserModel = { id: 0, email: "", password: "", username: "" };
    myform : FormGroup;
    submitted : boolean = false;

    ngOnInit(): void {
        this.myform = new FormGroup({
            username : new FormControl("", Validators.required),
            password : new FormControl("", Validators.required),
            confirmPassword: new FormControl("", Validators.required)
        },{ validator: PasswordValidation.MatchPassword })
    }
    constructor() {
    }
}

我收到以下错误:

  

类型的参数' {validator:(AC:AbstractControl)=>任何; }'不能分配给' ValidatorFn'类型的参数。     对象文字只能指定已知属性,并且'验证器'类型' ValidatorFn'

中不存在

我已附上截图以获得更清晰的信息。 enter image description here

以下是路径的项目文件夹层次结构:
enter image description here

2 个答案:

答案 0 :(得分:0)

import { PasswordValidation } from 'YOUR/CLASS/PATH/_utilities/_validations/validator.compare';

    this.myform = new FormGroup({
                username : new FormControl("", Validators.required),
                password : new FormControl("", Validators.required),
                confirmPassword: new FormControl("", Validators.required)
            },{ validator: MatchPassword });

错误说您没有指向正确的方法, 如果路径正确,只需调用该函数即可。

答案 1 :(得分:0)

您必须检查如何构建validatorFn。 https://angular.io/api/forms/ValidationErrors

定义方法的返回类型。