class-validator
class-validator copied to clipboard
Implement AllowIf decorator
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
Hey @kamilmysliwiec, it's my first contribution to an open-source project, if you need to change something in PR, just say so!
@chambber @kamilmysliwiec why this feature is not merged?
BTW we have this one too: https://stackoverflow.com/a/70128576/8784518
I would like to use this feature. Is there any chance it will end up in nestJs?