Angular4 中的自定义验证

Custom validation in Angular4

在我的页面中,我有一个简单的表单组。我必须在其中为名称编写自定义验证。

this.searchForm = this._formBuilder.group({

        profileName: new FormControl('', Validators.compose([Validators.required])),
        TypeId: new FormControl('', Validators.compose([Validators.required])),
        tempRange: new FormControl('', Validators.compose([Validators.required])),
        region: new FormControl('', Validators.compose([Validators.required])),
        quarter1: new FormControl('', Validators.compose([Validators.required])),
        quarter2: new FormControl('', Validators.compose([Validators.required]))

    }, {
            validator: this.customValidator// your validation method
        });

我已将自定义验证放在方法 this.customValidator 中。

我的验证之一是检查 profileName 的重复检查。

我在从验证方法 class 中获取同一类型脚本中的其他方法(验证逻辑所在的位置)时遇到问题,当我调用该方法(不是静态或函数)时,我我收到错误消息(按 f12

ERROR Error: Uncaught (in promise): TypeError: this.validateProfileName is not a function... '.

有没有什么方法可以调用特定的方法,或者我需要在它自己的验证方法中实现所有逻辑。

另外,如何以与必填字段验证错误消息相同的样式从那里显示验证错误消息。

我的验证方法

customValidator(control: AbstractControl) {
    debugger;
    let profileName = control.get('profileName').value;
    let retgionCode = control.get('regionCode').value;
    let forcastType = control.get('forecastTypeId');
    var status = this.validateProfileName(retgionCode, profileName);

    if (!status)
    control.get("profileName").setErrors({ 'invalidProfileName': true });

    return null;
}

看起来您做的工作比需要做的多,而且您也没有在自定义验证器中调用函数。这就是你想要的:

this.searchForm = this._formBuilder.group({
    profileName: ['', Validators.required],
    TypeId: ['', Validators.required],
    tempRange: ['', Validators.required],
    region: ['', Validators.required],
    quarter1: ['', Validators.required],
    quarter2: ['', Validators.required]
}, { validator: this.customValidator() });

然后在你的验证函数中,你需要这样做:

customValidator() {
    debugger;
    let profileName = this.searchForm.get('profileName').value;
    let retgionCode = this.searchForm.get('regionCode').value;
    let forcastType = this.searchForm.get('forecastTypeId');
    let status = this.validateProfileName(retgionCode, profileName);

    if (!status) {
        this.searchForm.get("profileName").setErrors({ 'invalidProfileName': true });
        return null;
    }
}

问题出在 this。正如您现在拥有的那样,您正在失去 this 的范围。在您的自定义验证器中, this 不指向您的组件范围,而是指向函数范围。并且函数范围内没有 validateProfileName,因此 Angular 给出了正确的错误。

要保留 this 的上下文,请绑定它:

validator: this.customValidator.bind(this)

现在您可以访问自定义验证器之外的范围了。