Custom Validator Help Angular 14

317 views Asked by At

I've been hung up on really understanding how to implement a custom validator inside of my reactive form.

I have 15 fields, 3 in which pertain to the custom validator "tcpPorts", "udpPorts", and "icmp" which is a check box. The logic that I want implemented is that at least ONE of these three fields have a value to be able to submit. At least one is required along with the other fields in the form.

How do I construct the right validator for this?

componen.ts my form

 newFWXForm = this.fb.group(
{
  sspSelect: ["", Validators.required],
  requester: [this.loggedInUser],
  requesterContactInfo: [this.loggedInUserEmail],
  fwxDescription: ["", Validators.required],
  durationTypeSelect: ["Permanent", Validators.required],
  durationDate: [""],
  infraSelect: [""],
  sourceIPs: ["", Validators.required],
  DestAnyCheck: [false],
  SrcAnyCheck: [false],
  icmp: [false, atleastOneValidator()],
  destinationIPs: ["", Validators.required],
  tcpPorts: ["", atleastOneValidator()],
  udpPorts: ["", atleastOneValidator()],
  addDirectory: new FormControl(false),
},
{ Validators: [] }

);

here is also a custom Validator function I started and tried a lot of different logic inside, help and knowledge would be greatly appreciated!

export function atleastOneValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {};
}

Thank you in advance!

1

There are 1 answers

0
akotech On

You could create a Validator for the FormGroup that checks the value of the 3 child FormControls.

It could be something like this.

export function atleastOneValidator(controlsNames: string[]): ValidatorFn {
  return (group: AbstractControl): ValidationErrors | null => {
  // Here include your validation logic of the controls. Im just checking for one truthy.
  const isValid = controlsNames.some(
    (fieldName) => group.get(fieldName)?.value
  );

  return isValid ? null : { atleastOneValidator: true };
};

}

And then add it to the FormGroup validators with passing an array of control names to check.

newFWXForm = this.fb.group(
  {
    ... //your controls 
  },
  { 
    validators: [atleastOneValidator(['icmp', 'tcpPorts', 'udpPorts'])]
  }
)

Cheers