0

In my application I want to apply compose validator conditionally and respective validators. I did with custom validator but doesn't get success.

this.myForm = this.builder.group({
   country:['',Validators.required],
   age:['',Validators.required],
   dependentName:['',Validators.compose([Validators.maxLength(20), Validators.required])]
})
  1. If country is 'America' and age is less than 18 then dependentName is required and max length should be 20.
  2. If the country is other than 'America' then dependentName field is not required but maxlength should be 20.

Please help.

2
  • 1
    You could add those validators dynamically, based on input value of the country stackoverflow.com/questions/43603605/… Commented Oct 22, 2018 at 5:14
  • Can you provide that custom validator that you try to create? Commented Oct 22, 2018 at 5:25

1 Answer 1

0

define your custome validator service and use it in formBuilder as given below

dependentName: ['',  [Validators.required, customValidationService.checkLimit(1,maxValue)]], /// provide your limit in place of minvalue and maxValue , like checkLimit(1,99)

in your **customValidationService **

import { AbstractControl, ValidatorFn } from '@angular/forms';

export class customValidationService {
   static checkLimit(min: number, max: number): ValidatorFn {
    return (c: AbstractControl): { [key: string]: boolean } | null => {
        if (c.value && (isNaN(c.value) || c.value < min || c.value > max)) {
            return { 'range': true };
        }
        return null;
    };
  }
}

Or

dependentName: [null, Validators.compose([Validators.required, Validators.minLength(5), Validators.maxLength(10)])]
Sign up to request clarification or add additional context in comments.

Comments

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.