Skip to content

Instantly share code, notes, and snippets.

@Klerith
Created July 16, 2022 16:32
Show Gist options
  • Save Klerith/c77edd9d86174aa68efbfddd21f053a2 to your computer and use it in GitHub Desktop.
Save Klerith/c77edd9d86174aa68efbfddd21f053a2 to your computer and use it in GitHub Desktop.
Password validation - DTO
@IsString()
@MinLength(6)
@MaxLength(50)
@Matches(
/(?:(?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/, {
message: 'The password must have a Uppercase, lowercase letter and a number'
})
password: string;
@DiegoDom
Copy link

Excelente pattern profe, ¡gracias!

@Navau
Copy link

Navau commented Aug 27, 2023

:v

@ramirez7358
Copy link

Buenas profe, una consulta.
¿En este caso se podria agregar a la expresion regular la limitacion de longitud verdad?
Pero entiendo que se elige usar @minlength y @maxlength por el error especifico que devuelve nest en caso de que esa restriccion se rompa, verdad?

Muchas gracias

@LumenMidgart
Copy link

Genial, muchas gracias (=

@Mceballos-git
Copy link

Un éxito, gracias Ferrrrrrr

@JorgeIPN7
Copy link

JorgeIPN7 commented Nov 21, 2023

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

export function IsEqualTo(
  property: string,
  validationOptions?: ValidationOptions,
) {
  return function (object: any, propertyName: string) {
    registerDecorator({
      name: 'isEqualTo',
      target: object.constructor,
      propertyName: propertyName,
      constraints: [property],
      options: validationOptions,
      validator: {
        validate(value: any, args: ValidationArguments) {
          const relatedValue = (args.object as any)[args.constraints[0]];
          return value === relatedValue;
        },
      },
    });
  };
}

//------------------------------------------

@IsString()
@MinLength(8)
@MaxLength(50)
@Matches(
  /(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)/, 
  { message: 'The password must include uppercase, lowercase letters, a number, and a special character.' }
)
password: string;

@IsString()
  @IsEqualTo('password', {
    message: 'Password confirmation does not match with password',
  })
  passwordConfirm: string;


@gabrielgjha1
Copy link

Bendiciones

@felipejoq
Copy link

Muchas gracias! 🤝

@manuelmtzv
Copy link

import {
IsStrongPassword,
} from 'class-validator';

@jpbizantino
Copy link

jpbizantino commented Jul 20, 2024

Recomiendo usar este decorador para controlar la fortaleza de la password. Ajustar los parámetros.

    @IsStrongPassword({
        minLength: 6,
        minLowercase: 1,
        minUppercase: 1,
        minNumbers: 1,
        minSymbols: 0,
    })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment