Search code examples
angularangular-directiveangular2-formbuilderangular-validator

Is there a way to access FormBuilder Validators in an Angular directive?


I've been trying to create a custom form validation directive in Angular 8 and I was wondering if it's possible to access the FormBuilder Validators attributes, such as, Required/minLength/maxLength inside my directive.

At the moment I'm handling the min/max values of an input by manually setting the min/max attributes on the HTML input

// form.component.html
<form
  customFormValidation // my directive
  class="form"
  [formGroup]="userForm"
  (ngSubmit)="onSubmit()">
 <div class="form-group">
  <label class="input-label">Username</label>
  <input
   type="text"
   minlength="5"
   maxlength="10"
   formControlName="username"
   name="username"
   class="form-control"/>
   ...
</form>

// form.component.ts
ngOnInit() {
this.userForm = this.fb.group({
  username: [
    "",
    [
      Validators.required,
      Validators.minLength(5),
      Validators.maxLength(10)
    ]
  ]
});
}

// customFormValidation.directive.ts
...
constructor(private renderer: Renderer2, private el: ElementRef) {}
@HostListener("submit", ["$event"])
onSubmit(e) {
e.preventDefault();
this.isSumbited = true;
for (const formInput of e.currentTarget.elements) {
  // For the simplicity of the example just logging the 
  minLength value of each input in the form 
  console.log(formInput.value.minLength); 
}
}

As seen above I'm handling the input min/max length by accessing the attributes provided in html but what I really want is to access the min/max from the FormBuilder Validators.

Any help is appreciated.


Solution

  • Why want to create directive for custom validator? You can learn how to create custom validator for FormGroup here: https://angular.io/guide/form-validation (Search “Custom validators” word in page)