From here: https://stackoverflow.com/a/42999816/462608
This is what I have tried:
whitespace-validator.directive.ts
import { Directive } from '@angular/core';
import { AbstractControl, FormControl, ValidationErrors } from '@angular/forms';
@Directive({
selector: '[appWhitespaceValidator]'
})
export class WhitespaceValidatorDirective
{
constructor() {}
static appWhitespaceValidator( control: FormControl ): ValidationErrors
{
const isWhitespace = (control.value || '').trim().length === 0;
const isValid = !isWhitespace;
return isValid ? null : { 'whitespace': true };
}
}
In xyz.ts
import { WhitespaceValidatorDirective } from '../whitespace-validator.directive'
...
this.objFormGroup = this.objFormBuilder.group(
{
blogTitle: [ this.blogs[this.mBlogId].title, [Validators.required, Validators.minLength(5) ] ],
body: [ this.blogs[this.mBlogId].body ],
category: [ this.blogs[this.mBlogId].category ]
} )
get getBlogTitle()
{
return this.objFormGroup.get('blogTitle') as FormControl;
}
In xyz.html
<div *ngIf = "getBlogTitle.errors?.appWhitespaceValidator">
No spaces are allowed.
</div>
Please show what is the correct way of using this validator directive. There are no errors here but the form is still not complaining w.r.t whitespaces.
What is the way to use the custom validator in HTML with "reactive" form?