代码之家  ›  专栏  ›  技术社区  ›  Varun

Angular 6被动窗体自定义验证器从默认数据中获取错误

  •  0
  • Varun  · 技术社区  · 7 年前

    我有一个自定义验证器,它检查每个FormArray中的所有数据,以验证数据的重复。目前,它还在用自身验证初始数据,这会引发一个错误。

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

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

    截图: enter image description here

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

    1 回复  |  直到 7 年前
        1
  •  1
  •   Wrokar    7 年前

    为了避免在原始数据上标记错误,可以添加检查以确保窗体控件 dirty

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