Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom Decorator Message #56

Closed
jerradpatch opened this issue Dec 22, 2016 · 4 comments
Closed

Custom Decorator Message #56

jerradpatch opened this issue Dec 22, 2016 · 4 comments
Labels
type: question Questions about the usage of the library.

Comments

@jerradpatch
Copy link
Contributor

Do custom validators not support a default message?

@pleerock
Copy link
Contributor

there is an option called dismissDefaultMessages you can specify into your validate method:

validator.validate(model, { dismissDefaultMessages: true })

@pleerock pleerock added the type: question Questions about the usage of the library. label Dec 23, 2016
@jerradpatch
Copy link
Contributor Author

jerradpatch commented Dec 23, 2016

gottcha. but what I was looking for was how to specify a default message in a custom validator. for example

export function IsLongerThan(property: string, validationOptions?: ValidationOptions) {
   return function (object: Object, propertyName: string) {
        registerDecorator({
            name: "isLongerThan",
            target: object.constructor,
            propertyName: propertyName,
            options: validationOptions,
            message: "here is the defualt message when 'message is not defined on the annotation itself'"
            validator: {
                validate(value: any, args: ValidationArguments) {
                   const [relatedPropertyName] = args.constraints;
                    const relatedValue = (args.object as any)[relatedPropertyName];
                    return  typeof value === "string" &&
                           typeof relatedValue === "string" &&
                           value.length > relatedValue.length; // you can return a Promise<boolean> here as well, if you want to make async validation
                }
            }
        });
   };
}

The use case would be if I have an annotation for validating 1 < X < 10, I can say in the custom annotation definition "value must be between 1 and 10" instead of having to repeat the text in the annotation decorator.

ie

@IsLongerThan("title", {
       message: "Text must be longer than the title"
    })

@patrickhousley
Copy link

patrickhousley commented Jul 16, 2017

@jerradpatch I just ran into this and was able to solve it by using a class validator as described here. Below is an example. If you would like to use just a decorator, then I assume the object you pass to validator just needs the defaultMessage(args: ValidationArguments) method implemented.

import { registerDecorator, ValidatorConstraint, ValidatorConstraintInterface, ValidationOptions, ValidationArguments } from 'class-validator';

@ValidatorConstraint({ name: 'matchesProperty', async: false })
export class MatchesPropertyConstraint implements ValidatorConstraintInterface {

    public validate(value: string, args: ValidationArguments) {
      const [relatedPropertyName] = args.constraints;
      const relatedValue = (args.object as any)[relatedPropertyName];
      return typeof value === typeof relatedValue &&
        value === relatedValue;
    }

    public defaultMessage(args: ValidationArguments) { // Set the default error message here
      const [relatedPropertyName] = args.constraints;
      return `$property must match ${relatedPropertyName} exactly`;
    }

}

export function MatchesProperty(property: string, validationOptions?: ValidationOptions) {
  return (object: Object, propertyName: string) => {
    registerDecorator({
      name: 'matchesProperty',
      target: object.constructor,
      propertyName,
      constraints: [property],
      options: validationOptions,
      validator: MatchesPropertyConstraint
    });
  };
}

@NoNameProvided
Copy link
Member

I am going to close this as @patrickhousley already showed the correct solution.

@typestack typestack locked and limited conversation to collaborators Jul 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
type: question Questions about the usage of the library.
Development

No branches or pull requests

4 participants