Home > database >  Custom input validator does not display an error as expected
Custom input validator does not display an error as expected

Time:07-11

I have simplified my app just to show the problem I am having with a custom validator.

You can see the app code on StackBlitz: validator.

My validator cannotContainSpace is definitely called by the framework because I can set a breakpoint on it but the message from the HTML template.

Password can not contain space.

is not displayed as I would expect.

In other words, when I enter some word with the space and press the Login button I would expect the error:

Password can not contain space.

to be displayed in the page content, but no error is displayed.

CodePudding user response:

The problem is from here:

password: [
  '',
  Validators.required, Validators.minLength(3), this.cannotContainSpace,
],

which you should wrap multiple Validators into an array such:

password: [
    '',
    [Validators.required, Validators.minLength(3), this.cannotContainSpace],
],

Sample StackBlitz Demo


References

Adding custom validators to reactive forms

  • Related