NestJs validation constraints

NestJs validation constraints

If you've coming from Laravel, you're probably used to simple validation rules that ease developers life with confirmed rule. On NestJs there is no such rules. On top of that to make NesJs more flexible it uses class-validator package which you can add to your project by running npm install --save class-validator.

So basically you need to create custom constraint decorator and apply it to the selected DTO field. For example:

export class RegisterUserDto {
    @IsString()
    @IsEmail()
    @IsNotEmpty()
    @IsDefined()
    email: string;

    @IsString()
    @Matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)\S+$/) // Regex for your password requirements
    @IsNotEmpty()
    @IsDefined()
    password: string;

    @IsString()
    @IsDefined()
    @Validate(PasswordConfirmConstraint, ['password'])
    password_confirm: string;
}

The key part is this @Validate(PasswordConfirmConstraint, ['password']) you add custom validation constraint .
To create custom constraint class must implement ValidatorConstraintInterface.

Example implementation of PasswordConfirmConstraint is following:

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

    defaultMessage(validationArguments?: ValidationArguments): string {
        return `"${validationArguments.property}" should be equal to "${validationArguments.constraints[0]}. Try again, but pay more attention :)"`;
    }

    validate(value: any, validationArguments?: ValidationArguments): Promise<boolean> | boolean {
        return value === validationArguments.object[validationArguments.constraints[0]];
    }

}

Consider consulting for more UX'y error messages with your Designer or UX specialist.

Have a nice day!