Search code examples
angularangular-formsangular-validation

Angular Form Custom Validators


I'm currently using Angular 8 and I have an issue with custom validator. The only validator that works is Validators.minLength(3). noEmptyStringValidator doesn't work, even though I can print 'here' into validator function. Could you help me?

The context is the following:

no-empty-string.validator.ts

import { AbstractControl } from '@angular/forms';

export function noEmptyStringValidator(control: AbstractControl): { [key: string]: any } | null {
    console.log('here');

    return control.value && control.value.trim().length > 0 ? { noEmptyString: { valid: true } } : null;
}

myComponent.component.ts

...
topicLabelControl = new FormControl();
...
this.topicLabelControl.setValidators([ Validators.minLength(3), noEmptyStringValidator ]);
...
console.log(this.topicLabelControl.valid);

myComponent.component.html

<mat-form-field appearance="outline"
      (keydown.enter)="handleEnterKey()">
      <input type="text"
        matInput
        [formControl]="topicLabelControl"
        [matAutocomplete]="auto" />
      <mat-autocomplete #auto="matAutocomplete">...
      </mat-autocomplete>
    </mat-form-field>

Solution

  • Your logic seems to be inverted: if the input is valid the validator should return null, if invalid an object whose key identifies the error. (The value can be anything, and can be used to report any additional information):

    return control.value && control.value.trim().length > 0 ? null : { noEmptyString: true };