1

Here is the formcontrol I am using. If the user enters Country US i need to set the validator as shown below (min length 5 max length 12)

lblzip1 = new FormControl('', Validators.compose([
        Validators.required,
        this.noWhitespaceValidator,
        Validators.pattern('^[a-zA-Z0-9- ]{5,15}$')
    ]));

IF the user enters any other country other than US I need to set the validator as shown below (min length 1, mx length 15)

lblzip1 = new FormControl('', Validators.compose([
        Validators.required,
        this.noWhitespaceValidator,
        Validators.pattern('^[a-zA-Z0-9- ]{1,15}$')
    ]));

Can you please let me know how do we do this in angular?

1 Answer 1

0

May be you can use a customer Validotor and after call him in your form. The validator will adjust the validation rules in base on your country selection. This is a sample of code: Custom Validator

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

export function zipCodeValidator(country: string): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    if (!control.value) {
      return null;
    }

    const value = control.value.trim();

   
    const countryValidationRules = {
      'US': { minLength: 5, maxLength: 12, pattern: /^[a-zA-Z0-9- ]{5,12}$/ },
      'default': { minLength: 1, maxLength: 15, pattern: /^[a-zA-Z0-9- ]{1,15}$/ }
    };

    
    const rules = countryValidationRules[country] || countryValidationRules['default'];

    
    if (value.length < rules.minLength || value.length > rules.maxLength) {
      return { length: true };
    }

   
    if (!rules.pattern.test(value)) {
      return { pattern: true };
    }

    
    return null;
  };
}

Sign up to request clarification or add additional context in comments.

1 Comment

That's NOT work if "country" is an input. When you define a FormControl with a validator, const country='US'; control=new FormControl('',customValidator(country)) the validator function "make inmutable" the value of the variable. The solution is make a customValidator that involve the two FormControls, see e.g. SO related to mannage two FormControls.

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.