Search code examples
validationangularangular-validation

Angular 2, custom validation messages with parameters


I'm just starting with JS/Typescript and Angular 2 and I'm struggling with the following.

export function MinImageDimensionsValidator(minWidth: number, minHeight: number): ValidatorFn {

return (control: AbstractControl): { [key: string]: any } => {

        // it's an image control where a user uploads an image.
        // the whole image related code has been removed for better readability. 
        //Just assume that 'actualWidth' holds the actual width of the image

        if(actualWidth < minWidth) {
           return { valid: false };
        }

        return null;
};

}

this is just a very basic example of a validator factory.

All the examples I found just wrote the validation messages/errors directly in the template (I'm using template forms)

Is it possible to "tie" the validation messages to the validator itself and use parameters with it?

like:

'Min width has to be 100. you supplied ' + actualWidth

this would be returned from the validator itself.

or is there another way (apart from storing everything in variables somewhere) ?


Solution

  • ValidatorFn should return a {[k:string]:any}, so it's as easy as this :

    export function MinImageDimensionsValidator(minWidth: number, minHeight: number): ValidatorFn {
      return (control: AbstractControl): { [key: string]: any } => {
        if (actualWidth < minWidth) {
          return {
            myValidator: `Min width has to be ${minWidth}. you supplied ${actualWidth}`
          };
        }
        return null;
      };
    }
    

    then you can access this error like myFormControl.errors.myValidator.