Conditional Validation¶
The conditional validation decorator (@ValidateIf) can be used to ignore the validators on a property
when the provided condition function returns false. The condition function takes the object being
validated and must return a boolean.
Basic Usage¶
import { ValidateIf, IsNotEmpty } from 'class-validator';
export class Post {
otherProperty: string;
@ValidateIf(o => o.otherProperty === 'value')
@IsNotEmpty()
example: string;
}
In this example, the validation rules applied to example won't be run unless the object's
otherProperty is "value".
Important Notes¶
- When the condition is false, all validation decorators are ignored, including
@IsDefined - The condition function takes the object being validated as a parameter
- The condition function must return a boolean
- Multiple
@ValidateIfdecorators can be used on the same property
Advanced Example¶
import { ValidateIf, IsNotEmpty, IsString } from 'class-validator';
export class User {
@IsString()
type: string;
@ValidateIf(o => o.type === 'admin')
@IsNotEmpty()
adminKey: string;
@ValidateIf(o => o.type === 'user')
@IsNotEmpty()
userKey: string;
}
Need documentation like this for your own product?
This site was built by Sonicar Tech LLC — we help SaaS, B2B, Enterprise, FinTech, and AI companies launch professional, docs-as-code documentation 60% faster and cheaper than building an in-house team, with first drafts delivered in 1 week.