0

I have the following attribute directive to perform form validation. My @NgModule includes it in it's declarations array. My form is in a component's template. How would I add the appCarrierFormValidation attribute to my form to be able to use this directive and validate the inputs?

import { Directive } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Directive({
  selector: '[appCarrierFormValidation]'
})
export class CarrierFormValidationDirective {

  addCarrierForm: FormGroup;
  constructor(private fb: FormBuilder) {
    this.createForm();
  }
  createForm() {
    this.addCarrierForm = this.fb.group({
      name: ['', Validators.required],
      email: ['',  [Validators.required, Validators.email]]
    })
  }
}
7
  • Can i see your code within the custom validator for appCarrierFormValidation? Commented Apr 9, 2019 at 15:09
  • I'm confused, appCarrierFormValidation is just the attribute selector to use in the template right? Commented Apr 9, 2019 at 15:12
  • Sorry, I miss out a few words before I edited it. Anyways, I misunderstood your question just now. Wait, what exactly are you trying to achieve? Where and when would you want those 2 FormControls to be validated? I.e, would you want the form fields to be validated immediately when the user keys in a value? Or upon submission of form? Commented Apr 9, 2019 at 15:13
  • I have a component, AddCarriersComponent whose template contains a form, form [formGroup]="addCarrierForm" This form contains those 2 controls that require validation. Commented Apr 9, 2019 at 15:16
  • why do you use Directive it's not a Component?????? Commented Apr 9, 2019 at 16:09

1 Answer 1

1

You can implement like this, I used in my project.

  import { FormControl } from '@angular/forms';

    export function appCarrierFormValidation(control: FormControl) {

        // change your logic to validate carrier
        let pattern = /[*\\/|":?><]/gi;
        //if validation fails, return error name & value of true
        if (pattern.test(control.value)) {
            return { validString: true };
        }
        //otherwise, if the validation passes, we simply return null
        return null;
    }

And use

name: ['', [Validators.required, appCarrierFormValidation]],

If you want to use formGroup

public appCarrierFormValidation() : ValidatorFn{
       return (group: FormGroup): ValidationErrors => {
          const name= group.controls['name'];
          const email= group.controls['email'];
          // add your logic here
          if (name.value.length < 6 && email.value.indexOf('@') < 0) {
             email.setErrors({invalid: true});
          } else {
             email.setErrors(null);
          }
          return;
    };
 }

Update your code

 createForm() {
    this.addCarrierForm = this.fb.group({
      name: ['', Validators.required],
      email: ['',  [Validators.required, Validators.email]]
    })
    this.addCarrierForm .setValidators(this.appCarrierFormValidation())
  }
Sign up to request clarification or add additional context in comments.

3 Comments

What is the pattern regular expression you're using? And in this method, I wouldn't need to add an attribute to the template?
This is a sample, you can change to your logic
I get a formGroup expects a FormGroup instance error in my template

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.