class-validator icon indicating copy to clipboard operation
class-validator copied to clipboard

question: How to create Conditional Custom Validation?

Open dennbagas opened this issue 6 years ago • 6 comments

Here is my DTO:

export class ApplyCashbackDto {
@IsNotEmpty()
promoCode: string

// Conditional Validation
extras: string
}

I was trying to conditionally validate the extras property based on promoCode property, but i have to check first to the DB if the promoCode need some extras data because not all the promoCode must include the extras property

How to achieve this custom coditional validation?

dennbagas avatar Aug 29 '20 19:08 dennbagas

Hi, you can take a look at the Conditional validation in the documentation.

ex:

export class ApplyCashbackDto {
  @IsNotEmpty()
  promoCode: string

  @ValidateIf(o => {
      // business logic to check if o.promoCode need extras property, return boolean
      // if false all validation decorators for this field are ignored
    })
  @IsNotEmpty()
  extras: string
}

Kiliandeca avatar Sep 05 '20 13:09 Kiliandeca

@ValidateIf() can be used to conditionally validate on a property based on other property from the object being validated. What i need is to conditionally validate based on data from other sources like from databases, in this case the promoCode property.

It is something like creating custom validation classes so i can inject my repository class and perform some query to the database, if the promoCode property match with the data from database then do validation, otherwise skip the validation.

dennbagas avatar Sep 07 '20 03:09 dennbagas

Hi @dennbagas

You can create a custom async validator that may access your database. Furthermore, if using a service container, you can connect it connect Class Validator to access services in your validator.

However, accessing your database in a validator has some limitations, as you cannot provide arguments on a per-validation basis.

NickKelly1 avatar Sep 07 '20 17:09 NickKelly1

Hi @NickKelly1

Yes, i can create custom async validator, but that wasn't an optional validator. Its like regular validator that validate the value is right or not.

What i want is a custom optional async validation. Something like @ValidateIf() but async version

dennbagas avatar Sep 09 '20 14:09 dennbagas

Currently, you can achieve this only if you put the optional validation logic in your async validator. Closing this as solved.

If the issue still persists, you may open a new Q&A in the discussions tab and someone from the community may be able to help.

NoNameProvided avatar Nov 13 '22 14:11 NoNameProvided

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

github-actions[bot] avatar Dec 14 '22 00:12 github-actions[bot]