0

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: enter image description here

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

1 Answer 1

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};
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Wrokar, the solution works fine, but I have a new problem. When I make changes to the second row to have the same values as the first one, the error message displays but when I make changes to values in the first one, the second one still shows the error unless I make changes to it again? Any solution for that??

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.