2

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) ?

2 Answers 2

3

Yes, you can return any object from the validator. In your case it could be something like

return { minImageDimensions: { min: minWidth, value: actualWidth } }

When displaying field validation errors, you can do this:

<input #myField="ngModel" [(ngModel)]="...">
<span *ngIf="myField.errors.minImageDimensions">
    Min width has to be {{ myField.errors.minImageDimensions.min }}.
    You supplied {{ myField.errors.minImageDimensions.value }}.
</span>

Or even better use some localization and messages with parameters. You can make a component that will take a field object and display all kinds of error messages you use in your application according to the myField.errors object.

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

Comments

1

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.

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.