Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
615 views
in Technique[技术] by (71.8m points)

regex - I want to make validation on confirm_password1 match with confirm_password2 class-validator nestjs


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

to achieve that you need to create a custom validator,see custom-validation-decorators

For your case, you can work this one:

 //isEqual.ts 
import { registerDecorator, ValidationOptions, ValidationArguments } from 'class-validator';

export function isEqual(property: string, validationOptions?: ValidationOptions) {
  return function (object: Object, propertyName: string) {
    registerDecorator({
      name: 'isEqual',
      target: object.constructor,
      propertyName: propertyName,
      constraints: [property],
      options: validationOptions,
      validator: {
        validate(value: any, args: ValidationArguments) {
          const [propertyNameToCheck] = args.constraints;
          const valueToCheck = (args.object as any)[propertyNameToCheck];
          return  value === valueToCheck ;
        },
        defaultMessage(args: ValidationArguments) {
          const [propertyNameToCheck] = args.constraints;
          return `$property must be equal to ${propertyNameToCheck} `;
        },
      },
      
    });
  };
}

to use this validator simply add isEqual decorator to the property you want to check :

     //import { isEqual } from './isEqual';
    export class ChagnePasswordDto {
  @ApiProperty({ example: '12345678' })
  @IsNotEmpty()
  @IsString()
  @MinLength(4)
  input_old_password: string;

  @ApiProperty({ example: 'yourNewPassword' })
  @IsNotEmpty()
  @IsString()
  @MinLength(4)
  confirm_password1: string;

  @ApiProperty({ example: 'yourNewPassword' })
  @IsNotEmpty()
  @IsString()
  @MinLength(4)
  @isEqual('confirm_password1')
  confirm_password2: string;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...