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

查看:18
本文介绍了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天全站免登陆