How can i access certain Values on Form via custom Validator

Issue

I have the need of some custom validation in my angular app and I wonder how the best way to go about it.

The first one is a text box which takes a email address and I need it to validate if the address is in a local array stored called emails. The problem is for me that this.emails data comes from a api call so its empty when the form is initialized. So is there a way to update the this.emails value in the validator ? And if not what would be a work around ?

  preferenceForm = new FormGroup({
    contactId : new FormControl({value: ''}, Validators.required),
    email: new FormControl({value: '', disabled: false}, [Validators.required, Validators.email, CustomValidators.emailAccountValidator([this.emails])]),
    optionA: new FormControl({value: true, disabled: false}),
    optionB: new FormControl({value: true, disabled: false}),

});

export class CustomValidators {
  static emailAccountValidator( myData : any) {
    return (control: AbstractControl): {[key: string]: any } | null => {
    const email: string = control.value

    let isInArray = myData.indexOf(email)  !== -1

    if(isInArray){
      return null
    } else{
      return { validLname: false }
    }
  }
}}

The other is that I have a checkboxes A – C and then D and the validation rule would be that either A or B or C or any combo of A – C is checked or only D. The problem is how to i access from the validation function all 4 values of the checkbox. The below code i used only to troubleshoot the value of the checkboxes but i always get undefined. Not sure what i am missing here ?

static optionValidator(control: AbstractControl) {
  const optionA: boolean = control.get('optionA')?.value; 
  const optionB: boolean = control.get('optionB')?.value; 
  const optionC: boolean = control.get('optionC')?.value; 
  const optionD: boolean = control.get('optionD')?.value; 



  console.log('Option A : ' + optionA)
  console.log('Option B : ' + optionB)
  console.log('Option C : ' + optionC)
  console.log('Option D : ' + optionD)
  return null
 
}

Solution

Actually i was able to fix the first issue without the async validator. I just went and after I got my data from the API patched the Validators with the new data which is now avail.

this.preferenceForm.controls['email'].setValidators(Validators.compose([Validators.required, Validators.email, CustomValidators.emailAccountValidator(this.emails)]))

This works now just as expected without any other changes. Not sure how an async Validator would have solved it since the validation was not async but the data wasn’t avail when we init the form

Answered By – MisterniceGuy

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.