Angular 2 Custom Validator That Depends On Another Form Control


Answer :

You are one step closer.

You need to attach your custom validator to the FormGroup instead, because it needs to know two FormControl (categories and mealTypes), so attaching to FormGroup will give the validator more broad view and access to the entire FormControl

To achieve that, change your ngOnInit to

ngOnInit() {     this.findForm = new FormGroup({         mealTypes : new FormControl(null, Validators.Required),         categories : new FormControl(null)         // others form control here     }, validateMealType); // <-- see here is your custom function } 

On above code, you actually have to use FormGroup constructor instead of FormBuilder, so you can attach your custom validation in the parameters. Also, move your custom validator outside the component class.

Take a look at this Plunker to get more insight for your specific case here.


The solution proposed by @Michael worked for me with a minor change for the Angular 4.

In the validation function, I needed to change the parameter type from AbstractControl to FormGroup because the AbstractControl in this version does not contain the controls collection.

function validateEqual(form: FormGroup): { [key: string]: boolean } {   const senha = form.controls['novaSenha'];   const confirmacaoSenha = form.controls['confirmacaoNovaSenha'];    if (senha != undefined && confirmacaoSenha != undefined) {     const senhaValue = senha.value;     const confirmacaoSenhaValue = confirmacaoSenha.value;      if (senhaValue !== confirmacaoSenhaValue) {         return { 'A senha e a confirmação não coincidem.': true};     }      return null;   } } 

Thanks too, @Ariel who founds this post.


You can navigate your way through the control and its parent form group to another control:

example(): ValidatorFn {      return (control: AbstractControl): ValidationErrors | null => {          const forbidden = control.value < control.parent.controls["anotherControl"].value;          return forbidden ? { forbidden: { message: "Custom message" } } : null;      }; } 

Add the above as a function inside your component and declare this validator to your form control:

formGroup = new FormGroup({     //..     targetControl: new FormControl("", [this.example()]),     anotherControl: new FormControl("")     //.. }); 

Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable