Varun
Varun

Reputation: 3735

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

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

Upvotes: 0

Views: 617

Answers (1)

Wrokar
Wrokar

Reputation: 963

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

Upvotes: 1

Related Questions