Reputation:
I use the reactive forms in Angular.
<input type="text" name="name" formControlName="name">
How to apply validation rule (custom or default Validators.required
) for this input using directive?
Upvotes: 2
Views: 396
Reputation: 214017
There are many built-in directives that apply some built-in Validators:
RequiredValidator directive applies Validators.required
validator
<input type="text" name="name" formControlName="name" required>
^^^^^^^^
EmailValidator directive uses Validators.email
validator
<input type="text" name="name" formControlName="name" [email]="true">
^^^^^^^^^^^^^^
MinLengthValidator directive uses Validators.minLength
validator
<input type="text" name="name" formControlName="name" minlength="4">
^^^^^^^^^^^^^
MaxLengthValidator directive uses Validators.maxLength
validator
<input type="text" name="name" formControlName="name" maxlength="10">
^^^^^^^^^^^^^^
PatternValidator directive uses Validators.pattern
validator
<input type="text" name="name" formControlName="name" pattern="[a-zA-Z ]*">
^^^^^^^^^^^^^^^^^^^^
But you can also create your own custom directive to apply validation rule. You just need to implement Validator interface, e.g.
ts
@Directive({
selector: '[customValidator]',
providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}]
})
class CustomValidatorDirective implements Validator {
validate(control: AbstractControl): ValidationErrors|null {
return {'custom': true};
}
}
html
<input type="text" name="name" formControlName="name" customValidator>
^^^^^^^^^^^^^^^
You can even use @Input
property in order to customize logic inside validator
ts
@Directive({
selector: '[customValidator]',
providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}]
})
class CustomValidatorDirective implements Validator {
@Input() customValidator: string;
validate(control: AbstractControl): ValidationErrors|null {
return control.value !== this.customValidator ? {'notYurzui': true} : null;
}
}
html
<input type="text" name="name" formControlName="name" customValidator="yurzui">
^^^^^^^^^^^^^^^^^^^^^^^^
If it is not enough for you and you want to validate asynchronously then you can create async equivalent of custom directive:
@Directive({
selector: '[customAsyncValidator]',
providers: [{
provide: NG_ASYNC_VALIDATORS,
useExisting: CustomAsyncValidatorDirective,
multi: true
}]
})
class CustomAsyncValidatorDirective implements AsyncValidator {
validate(control: AbstractControl): Observable<ValidationErrors|null> {
return of({'custom': true});
}
}
Upvotes: 2