1

I want to create a custom validation function for my form group which validates the input of the country matches to my country list item.

This is my country list:

this.sharedService.getCountry().subscribe(res => {
  res.map(item => {
    this.countryList.push(item);
  });
});

my form is:

this.form = fb.group({
    country: new FormControl('', [Validators.required]),
});

1 Answer 1

1

You need to write a custom validator service which checks for the input as follows,

function check_if_valid(value,array){
   if((alue){ 
       const isInArray = array.includes(value);
       return true;
   } else {
       return false;
   }
}

@Injectable()
export class ValidatorsService {

   public isInteger = (control:FormControl) => {
        return check_if_valid(control.value,yourarray);
   }

}

and in component

constructor(private _ValidatorsService: ValidatorsService){
    }

country: new FormControl('', [Validators.required,this._ValidatorsService.isInteger ]),
Sign up to request clarification or add additional context in comments.

5 Comments

so how do I call my array?
can I call it in constructor() ?
you can make the api call in service itself unless you are not using in your component
I get the error when I write this._ValidatorsService.isInteger in formControl
TS2345:Argument of type '(((control: AbstractControl) => ValidationErrors) | ((control: FormControl) => boolean))[]' is not assignable to parameter of type 'ValidatorFn | ValidatorFn[] | AbstractControlOptions'. Type '(((control: AbstractControl) => ValidationErrors) | ((control: FormControl) => boolean))[]' has no properties in common with type 'AbstractControlOptions'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.