M
M
Mikhail2020-06-01 22:31:11
Angular
Mikhail, 2020-06-01 22:31:11

How to create an array element validator?

Good evening.
There is a need to check the presence of an element in the array by the value from the input and issue an appropriate message. I do it like this:

export function inArrayValidator(array: Array<Tag>): ValidatorFn {
    return (control: AbstractControl): {[key: string]: any} | null => {
        const forbidden = array.filter( i => i.name == (control.value !== null ? control.value.trim().toLowerCase() : null)).length != 0;
        return forbidden ? {'inArray': {value: control.value}} : null;
  };
}
...
export class TagListComponent  implements OnInit {
    public tagFormGroup: FormGroup;
    private tagSubscription: Subscription;
    ngOnInit() {
        this.tagFormGroup= new FormGroup({
            name: new FormControl(null)
        });

        this.tagSubscription = this.tagFormGroup.get('name').valueChanges.subscribe(_ => {
            this.tagFormGroup.get('name').setValidators([Validators.required, inArrayValidator(this.tags)]);
        });
    }
}


Maybe there is some more elegant solution without constant setValidators ?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question