1

I want to add validation on dynamically generated field. This is my code.

projectForm: FormGroup;

constructor(private sanitizer:DomSanitizer,private router: Router,private fb: FormBuilder,private projectService: ProjectService,private fnService:FunctionsService, private  userService : UserService) {      

    this.projectForm = fb.group({
        'shirnkrap':[null, Validators.required],
        'cd_text':[null, Validators.required],
        'assignto':[null, Validators.required],
        'projecttype':[null, Validators.required]

    });
}

on one function i want to add new validation which will trigger on <select>change event.

I try this,

this.projectForm.controls['project_name'].setValidators([Validators.required]); but it give me this error,

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'setValidators' of undefined

So can someone help me how can i add validation?

Jota.Toledo
  • 27,293
  • 11
  • 59
  • 73
Archish
  • 850
  • 8
  • 32

2 Answers2

1

Your problem is not exactly with adding a validator to your form. It's more adding a control dynamically to your form.

Unfortunately, it looks like it's not something that is feasible with the method addControl. As per documentation, you should only use addControl() when you are instantiating the form.

So, how to deal with dynamic controls? 2 things are feasible: the first one, that looks too complicated would be to use a FormArray. Have a look at this answer for more information : How to dynamically add and remove form fields in Angular 2

The second one would be to initialize your form directly with your dynamic field:

this.projectForm = fb.group({
    'shirnkrap':[null, Validators.required],
    'cd_text':[null, Validators.required],
    'assignto':[null, Validators.required],
    'projecttype':[null, Validators.required],
    'project_name': ''
});

Inside your template, you would only have to hide that field based on your condition (using ng-if="my-selected-value === 'someValue'"

Then, on your <select> change, you would have to add your validator :

if(my-selected-value === 'someValue') {
    this.myForm.controls["firstName"].setValidators([Validators.required]);
    this.myForm.updateValueAndValidity();
}

Do not forget to update the validity of your form. Otherwise you will have to wait for the user to update a field before seeing that your form is not valid anymore.

You can see an example on Deborah Kurata's tutorial on Reactive Form here:

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Deblaton Jean-Philippe
  • 11,188
  • 3
  • 49
  • 66
-3

Use following code to add validation dynamically:

this.myForm.controls["firstName"].setValidators([Validators.required]);

Your formGroup object don't have project_name field. You can also add formcontrol dynamically in your formgroup object.

this.projectForm.addControl("project_name", new FormControl(null));

Hope it will help

Sandip Jaiswal
  • 3,428
  • 2
  • 13
  • 15