> ## Content Index
> Fetch the complete content index at: https://www.karls.io/llms.txt
> Use this file to discover other available public pages before exploring further.

# NestJs validation constraints
- URL: https://www.karls.io/nestjs-validation-constraints/
- Published: 2020-02-29T09:11:00.000Z
- Updated: 2023-12-30T00:30:04.000Z
- Author: Karl Scerbiakas

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:

```javascript
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: 

```javascript
@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!