1

我正在从参考 scotch.io 网站学习 Angular2 Custom Validation for Repeat password for Registry form:
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() {
    }
}

我收到以下错误:

'{验证器类型的参数:(AC:AbstractControl)=>任何;}' 不可分配给“ValidatorFn”类型的参数。对象字面量只能指定已知属性,而“ValidatorFn”类型中不存在“validator”

为了更清楚,我附上了屏幕截图。 在此处输入图像描述

以下是路径的项目文件夹层次结构:
在此处输入图像描述

4

2 回答 2

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 });

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

于 2017-10-31T06:26:45.800 回答
0

您必须检查如何构建验证器Fn。https://angular.io/api/forms/ValidationErrors

定义方法的返回类型。

于 2017-10-31T07:28:24.177 回答