Angular 6 Reactive Forms Custom Validator从默认数据中显示错误 [英] Angular 6 Reactive Forms Custom Validator getting error shown from Default Data

查看:82
本文介绍了Angular 6 Reactive Forms Custom Validator从默认数据中显示错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个FormGroup中有一个FormArray,并且每个FormArray都有多个FormGroup,并且可以动态添加它们.

I have a FormArray in a FormGroup and each of the FormArray has multiple FormGroup's and can add them dynamically.

我有一个自定义验证器,它在其中检查每个FormArray中的所有数据以验证数据的重复.目前,它也正在使用本身正在验证的初始数据进行验证.

I have a Custom Validator where it checks with all the data in each of the FormArray to validate the repetition of data. Currently, it's also validating the initial data with itself which is throwing an error.

在检查初始数据时,是否有任何方法可以限制错误免于引发错误?

添加新数据并具有与现有数据相同的值时,它工作正常.

It's working fine when new data is added and has same values as the existing one's.

for (let assign of this.additionalAssign) {
      const fg = new FormGroup({
        "payRate": new FormControl(assign.jobRate, Validators.required),
        "position": new FormControl(assign.position, Validators.required),
        "location": new FormControl(assign.location, Validators.required),
        "department": new FormControl(assign.department, Validators.required)
      }); 
      fg.validator = this.jobDataValidator.bind(this);
      this.addPay.push(fg);
    }

验证者:

jobDataValidator(control: FormControl): {[s: string]: boolean} {
        let value = this.getJobLocDeptValidity(control);
        if(value.length > 0){
          return {'sameJobData': true};
        }
        return null;
      }

getJobLocDeptValidity(control: FormControl):any[] {
            let additionalAssignments = this.additionalAssignmentsForm.value.payArray;
            let test = additionalAssignments.filter(item =>  !!control.value.position && item.position ===              !control.value.location && item.location === control.value.location);
            return test;
          }

截屏:

Stackblitz网址: https://stackblitz.com/edit/angular-custom-验证程序默认数据

Stackblitz Url: https://stackblitz.com/edit/angular-custom-validator-defaultdata

推荐答案

为避免在原始数据上标记此错误,可以添加检查以确保表单控件为dirty,这表示用户已触摸它.

To avoid this marking an error on the original data, you can add a check to make sure the form control is dirty, meaning that a user has touched it.

if(value.length > 0 && control.dirty){
      return {'sameJobData': true};
}

这篇关于Angular 6 Reactive Forms Custom Validator从默认数据中显示错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆