How to add validator dynamically to FormControl in Angular 2

I use ReactiveFormsModule and defined all my form elements, including simple validators such as Validators.required in the const configuration.

I wanted to add a special validator to one of these FormControls.

Currently, I have added a custom validator as a function inside this configuration, and it works fine, but it doesn’t belong here, it really should live inside my component, but I'm not sure how I can simply attach a custom validator manually after FormBuilder configured all my controls.

See below comment code that looks like

How can I attach here

* ??? *

this.form.get ('site_id'). add custom valiator

This is my current configuration code.

 import {FormControl, Validators, FormBuilder} from '@angular/forms'; var fb = new FormBuilder(); function exampleValidator(control: FormControl): { [s: string]: boolean} { if (control.value === 'Example'){ return { example: true }; } return null; } export const formConfig = fb.group({ 'extract_batch_id': ['bbbbbbbbbbbbb', [ Validators.required ]], 'site_id': ['blah', [ Validators.required, exampleValidator ]] }); 

I have a directive that really needs to store a custom validator

Job Search Component

 import {Component, Input, OnInit, OnDestroy} from '@angular/core'; import {FormGroup, FormControl} from '@angular/forms'; import {ActivatedRoute} from '@angular/router'; import {Subscription} from 'rxjs'; import {Job} from '../../../models/job'; import {JobService} from '../../../services/api/job.service'; import {DebugService} from '../../../common/debug/debug.service'; import {formConfig} from './edit.form-config'; @Component({ selector: 'wk-job-search-edit', template: require('./edit.html') }) export class JobSearchEditComponent { form: FormGroup; job: Job; @Input() jobId: number; private subscription: Subscription; constructor( private route: ActivatedRoute, private jobService: JobService, private debug: DebugService){ // Configure form FormGroup via exported formConfig this.form = formConfig; // How do I Attach Here // *** ??? *** // this.form.get('site_id').add custom valiator } /* exampleValidator(control: FormControl): { [s: string]: boolean} { if (control.value === 'Example'){ return { example: true }; } return null; } */ } 

JobSearch Edit.html

 <form [formGroup]="form" (ngSubmit)="onSubmit()"> <button type="submit" class="btn btn-success" [disabled]="!form.valid">Save</button> <div class="form-group" [ngClass]="{'has-danger':!form.get('extract_batch_id').valid}"> <label for="extract_batch_id" class="form-control-label">Extract Batch</label> <input id="extract_batch_id" formControlName="extract_batch_id" type="text" placeholder="Extract Batch" class="form-control input-sm"> <div *ngIf="!form.get('extract_batch_id').valid"> <div class="form-control-feedback">Extract Batch is required?</div> <small class="form-text text-muted">Please enter a Extract Batch, eg. xyz.</small> </div> </div> <div class="form-group" [ngClass]="{'has-danger':!form.get('site_id').valid}"> <label for="site_id" class="form-control-label">Site</label> <input id="site_id" formControlName="site_id" type="text" placeholder="Site" class="form-control input-sm"> <div *ngIf="!form.get('site_id').valid"> <div class="form-control-feedback">Site is required?</div> <small class="form-text text-muted">Please enter a Site, eg. xyz.</small> </div> </div> </form> 
+7
validation angular angular2-forms
source share
2 answers

By looking at your code, what you can do:

 <div class="form-group" [ngClass]="{'has-danger':!form.get('site_id').valid}"> <label for="site_id" class="form-control-label">Site</label> <input id="site_id" [formControl]="site_id_control" type="text" placeholder="Site" class="form-control input-sm"> <div *ngIf="!form.get('site_id').valid"> <div class="form-control-feedback">Site is required?</div> <small class="form-text text-muted">Please enter a Site, eg. xyz.</small> </div> </div> 

See [formControl] = "site_id_control"

Then, in this way, you can add or remove validators from this specific control as follows:

inside your class:

 export class JobSearchEditComponent { private site_id_control=this.form.controls['site_id']; updateValidator(){ let exisitingValidators = this.site_id_control.validators; this.site_id_control.setValidators(Validators.compose([...existingValidators , exampleValidator])) // you probably also need this : this.site_id_control.updateValueAndValidity(); } } 
+13
source share

Add custom validator in angular2 Reactive form:

 this.yourForGroup = this.formBuilder.group({ 'yourKey': ['',[Validators.required,this.yourFunctionName]] )} this.yourFunctionName(control: FormControl){ return your operations.. } 
0
source share

All Articles