creating and use validators to report errors when the input value (entered by user) is not in a defined list, is not that complicated. Here is a simple example:

1 – First, let us create our component with a FormControl and validators. Then Use the form in our component’s template.

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-Brice-Nguenkam',
  template: `
    <form [formGroup]="myForm">
      <input formControlName="myField" />
      <div *ngIf="myForm.get('myField').hasError('notIncluded')">
        Invalid selection. Please select a value from the list.
      </div>
    </form>
  `,
})
export class MyComponent {
  myForm: FormGroup;

  optionsList:string[] = ['Option1', 'Option2', 'Option3'];
  constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
      myField: ['', [Validators.required, this.myIncludedValidator(this.optionsList)]],
    });
  }

  myIncludedValidator(options: string[]) {
    return (control) => {
      const value = control.value;
      if (options.includes(value)) {
        return null; // No error if the value is in the list
      } else {
        return { notIncluded: true }; // Error if the value is not in the list
      }
    };
  }
}

2 – Use validator:

Here a custom validator called “myIncludedValidator” is created which ensures that the entered value is included in the specified list (Here “optionsList“). The validator is then used in our component’s FormGroup.

By Shabazz

Software Engineer, MCSD, Web developer & Angular specialist

Leave a Reply

Your email address will not be published. Required fields are marked *