Angular4

时间:2018-02-19 14:00:46

标签: angular angular2-forms angular4-forms

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

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的重复检查。

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

  

错误错误:未捕获(在承诺中):TypeError:   this.validateProfileName不是函数......'。

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

此外,如何以与所需字段验证错误消息相同的样式显示验证错误消息。

我的验证方法

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

2 个答案:

答案 0 :(得分:3)

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

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

validator: this.customValidator.bind(this)

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

答案 1 :(得分:0)

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

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