0
\$\begingroup\$

I am working with angular and I have created a custom validator that checks if an input has a value from a drop-down, If the value inside the input is not one in the list then the validator should throw an error.

This is my implementation but I am a bit hesitant about how I am initializing the form control.

// populating states on loading of the component
    regionsByApi()
      .then((response) => {
        this.states = response.data.map((item) => {
          return {
            key: this.titleCase.transform(item),
            value: this.titleCase.transform(item),
          };
        });
        this.stateFormControl.setValidators([
          Validators.required,
          autoCompleteSelectValidator(this.states),
        ]);
        this.stateFormControl.setValue('California', { onlySelf: true });
      })
      .catch(() => {
        Notify.failure(`Oops webpage did't load properly, reload again.`);
      });

Custom validator

export const autoCompleteSelectValidator = (
  options: Options[]
): ValidatorFn => {
  return (control: AbstractControl): { [key: string]: boolean } | null => {
    const val = options.some((item) => {
      if (item.key.toLowerCase() === control.value.toLowerCase()) return true;
      return false;
    });
    console.log(val);
    if (!val) return { validAutoCompleteOption: true };
    else return null;
  };
};

Please review and advise!

\$\endgroup\$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.