乐闻世界logo
搜索文章和话题

How to use else condition in validationif decorator nestjs class-validator?

1个答案

1

In NestJS's class validator (class-validator), the @ValidateIf() decorator is typically used to apply validation rules under specific conditions. If you need to apply alternative validation rules when a condition is not satisfied (i.e., the 'else' condition), you usually need to use another @ValidateIf() to specify the negated condition of this condition.

Here is a simple example to illustrate this:

Suppose we have a user registration feature where the user must provide at least one of email or phoneNumber. We will use @ValidateIf() to ensure that if email is not provided, then phoneNumber must be valid, and vice versa.

typescript
import { IsEmail, ValidateIf, IsMobilePhone } from 'class-validator'; export class RegisterDto { @ValidateIf(o => !o.phoneNumber) @IsEmail() email?: string; @ValidateIf(o => !o.email) @IsMobilePhone() phoneNumber?: string; }

In this example:

  • The first @ValidateIf() decorator checks if phoneNumber is not provided; if not, then the email field must be a valid email address.
  • The second @ValidateIf() decorator checks if email is not provided; if not, then the phoneNumber field must be a valid mobile phone number.

In this way, we achieve the 'if...then...else...' logic, ensuring that the user provides at least one contact method and that the provided information is valid. This approach is very useful for handling complex conditional validation logic, allowing flexible data validation.

2024年8月16日 02:31 回复

你的答案