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

Implement AllowIf decorator

Open chambber opened this issue 3 years ago • 3 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

chambber avatar Feb 24 '22 13:02 chambber

Hey @kamilmysliwiec, it's my first contribution to an open-source project, if you need to change something in PR, just say so!

chambber avatar Feb 24 '22 17:02 chambber

@chambber @kamilmysliwiec why this feature is not merged?

BTW we have this one too: https://stackoverflow.com/a/70128576/8784518

kasir-barati avatar May 10 '22 08:05 kasir-barati

I would like to use this feature. Is there any chance it will end up in nestJs?

burriedu2 avatar Aug 10 '23 19:08 burriedu2