Template Form no empty string at beginning directive validator
February 2, 2024 · 2 min readLucian CiobanuTemplate driven forms are rarely used because in my experience, the data and forms are a bit more difficult to work with although, in theory, Angular provides all the documentation needed.
In this article, I'm going to show how I implemented a custom validator with a directive which accepts an reg exp pattern.
regExpValidator.directive.ts
import { Directive, Input } from '@angular/core';
import { AbastractControl, NG_Validators, ValidationErrors, Validator } from '@angular/forms';
@Directive({
standalone: true,
selector: '[appRegExpValidator]',
providers: [
{
provide: NG_VALIDATORS,
useExisting: RegExpValidatorDirective,
multi: true,
},
],
})
export class RegExpValidatorDirective implements Validator {
@Input() appRegExpValidator: RegExp | undefined;
validate(control: AbstractControl): ValidationErrors | null {
if (this.appRegExpValidator) {
const invalidRegExp = this.appRegExpValidator.test(control.value);
return invalidRegExp ? { invalidRegExp: { value: control.value } } : null;
} else {
return null
}
}
}
Given that the directive is standalone, we just import it in the component we want to use it
usingDirective.component.ts
...
@Component({
...
imports: [
RegExpValidatorDirective
],
}),
export class UsingDirectiveComponent {
noWhiteSpaceRegExp: RegExp = /^\s+/;
...
}
usingDirective.component.html
<input
[(ngModel)]="something.property" //important to have different name from temp var
#something=ngModel //this is done to have the error on something template variable
[appRegExpValidator]="noWhiteSpaceRegExp"
/>
<small *ngIf="something?.errors?.['invalidRegExp']>
Invalid inserted value
</small>
And here it is! I felt this challenging from numerous perspectives - making the directive accept a parameter, and also to pass a regExp as a param.
Hope this helped!
Cheers,
Lucian

Web Development & Software Delivery