Jim
Jim

Reputation: 181

Angular 4 FormGroup value match array item

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]),
});

Upvotes: 1

Views: 1086

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222582

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 ]),

Upvotes: 1

Related Questions