question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

feat: add decorator to check if two properties match

See original GitHub issue

First of all, thanks for the awesome validation solution! I use class-validator in my NestJS setup. Now I want to know if and how it is possible to check if two values match with eachother. Let’s say I have a dto setup like this:


export class UserCreateDto {
  @IsString()
  @IsNotEmpty()
   firstName: string;

   @IsEmail()
   emailAddress: string;

   @DoesMatch(o => o.emailAddress === o.emailAddressConfirm) // <---- check if email's match
   @IsEmail()
   emailAddressConfirm: string;
}

Issue Analytics

  • State:open
  • Created 4 years ago
  • Reactions:17
  • Comments:15 (3 by maintainers)

github_iconTop GitHub Comments

29reactions
PieroMacalusocommented, Mar 31, 2020

Hi! I am posting there the solution I found to implement this control. It refers to my question/answer on StackOverflow. I am going to provide a suitable solution for this particular issue.

user-create.dto.ts

export class UserCreateDto {
   @IsString()
   @IsNotEmpty()
   firstName: string;

   @IsEmail()
   emailAddress: string;

   @Match('emailAddress')
   @IsEmail()
   emailAddressConfirm: string;
}

match.decorator.ts

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

export function Match(property: string, validationOptions?: ValidationOptions) {
    return (object: any, propertyName: string) => {
        registerDecorator({
            target: object.constructor,
            propertyName,
            options: validationOptions,
            constraints: [property],
            validator: MatchConstraint,
        });
    };
}

@ValidatorConstraint({name: 'Match'})
export class MatchConstraint implements ValidatorConstraintInterface {

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

}

I managed to solve a similar problem on my personal project. Hope it helps!

17reactions
LeonardoRosaacommented, Dec 15, 2020

@mrpharderwijk and @pieromacaluso, it’s works for me. Thanks!!

Full code:

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

export function Match(property: string, validationOptions?: ValidationOptions) {
    return (object: any, propertyName: string) => {
        registerDecorator({
            target: object.constructor,
            propertyName,
            options: validationOptions,
            constraints: [property],
            validator: MatchConstraint,
        });
    };
}

@ValidatorConstraint({name: 'Match'})
export class MatchConstraint implements ValidatorConstraintInterface {

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

    defaultMessage(args: ValidationArguments) {
      const [relatedPropertyName] = args.constraints;
      return `${relatedPropertyName} and ${args.property} don't match`;
    }
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

Is it possible to validate that one of 2 parameters are present ...
First, you must add a custom validation class (read document) and then define a custom decorator for that (read document).
Read more >
PythonDecoratorLibrary - Python Wiki
This page is meant to be a central repository of decorator code pieces, whether useful or not <wink>. It is NOT a page...
Read more >
The @property Decorator in Python: Its Use Cases ...
2️⃣ Intro to Decorators​​ It lets us add new functionality to an existing function without modifying it. Let's analyze these elements in detail:...
Read more >
Python Property Decorator - GeeksforGeeks
Which is used to return the property attributes of a class from the stated getter, setter and deleter as parameters. Now, lets see...
Read more >
API — Flask Documentation (2.2.x)
Once it is created it will act as a central registry for the view functions, the URL rules, ... you should create it...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found