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

feat: Add AllowIf Decorator

Open burriedu2 opened this issue 2 years ago • 0 comments

PR Checklist

Please check if your PR fulfills the following requirements:

  • [x] The commit message follows our guidelines: https://github.com/nestjs/nest/blob/master/CONTRIBUTING.md
  • [x] Tests for the changes have been added (for bug fixes / features)
  • [x] Docs have been added / updated (for bug fixes / features)

PR Type

What kind of change does this PR introduce?

  • [ ] Bugfix
  • [x] Feature
  • [ ] Code style update (formatting, local variables)
  • [ ] Refactoring (no functional changes, no api changes)
  • [ ] Build related changes
  • [ ] CI related changes
  • [ ] Other... Please describe:

What is the current behavior?

There is currently no way to define whether a property is conditionally whitelisted, for example:

enum TypesCancel = {
  USER: 'user',
  STOCKOUT: 'stockout',
  OTHERS: 'others',
}

class CancelDTO {
  @IsEnum(TypesCancel)
  @IsNotEmpty() 
  type: TypesCancel;

  // if the type === TypesCancel.OTHERS, reason is required, but if not, must not sent
  @Optional() // with optional, it still receives even if the type !== TypesCancel.OTHERS
  @IsString()
  reason?: string;
}

const cancel = new CancelDTO();
cancel.type = TypesCancel.USER;
cancel.reason = 'reason';

validate(cancel).then(errors => {
  // cancel.reason is defined
});

Issue Number: https://github.com/typestack/class-validator/issues/1489

What is the new behavior?

enum TypesCancel = {
  USER: 'user',
  STOCKOUT: 'stockout',
  OTHERS: 'others',
}

class CancelDTO {
  @IsEnum(TypesCancel)
  @IsNotEmpty() 
  type: TypesCancel;

  @AllowIf(cancel => cancel.type === TypesCancel.OTHERS) // with AllowIf, the reason was accept if type === TypesCancel.OTHERS
  @IsString()
  reason?: string;
}

const cancel = new CancelDTO();
cancel.type = TypesCancel.USER;
cancel.reason = 'reason';

validate(cancel).then(errors => {
  // errors = reason should not exist
  // cancel.reason is not defined
});

Does this PR introduce a breaking change?

  • [ ] Yes
  • [x] No

Other information

This PR contains all changes from #86 but it has been rebased since the master has changed since it was submitted. It also updates the behavior to work as expected if forbidNonWhitelisted is set.

burriedu2 avatar Aug 16 '23 18:08 burriedu2