Angular 6 Reactive Forms Custom Validator getting error shown from Default Data

馋奶兔 提交于 2019-12-11 15:41:19

问题


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

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.

Is there any way to restrict the error from throwing itself when it's checking the initial data.?

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

Validator:

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

Screenshot:

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


回答1:


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


来源:https://stackoverflow.com/questions/52882284/angular-6-reactive-forms-custom-validator-getting-error-shown-from-default-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!