Suppose I have something like this.
class UpdateUserDTO {
@IsString()
readonly status: string;
@IsBoolean()
readonly deleted: boolean;
@IsString()
readonly name: string;
}
I want to validate this so that the class can only have either status or deleted defined. It doesn't matter if name is defined or not, but if status is defined, then deleted cannot be defined and vice versa.
Any way to make that work?
Yes I was thinking if there was some way I could use @ValidateIf, but I don't see how yet. I could put @ValidateIf(o => o.status != undefined) on deleted, and have something that would always fail the validation. But that would be a bit of a clunky solution, and I still want to perform other validations like @IsBoolean even if status is undefined.
It's been a while since this issue was created, but here's the solution I came up with for this use case. I had the same requirement, and it seems like a pretty common requirement.
What you're looking to do would currently require the combination of a custom validator and ValidateIf. You end up with two validations, one validates if there a property present that cannot exist on the same instance as the validated property, and the other determines if a property should be validated.
// Define new constraint that checks the existence of sibling properties
@ValidatorConstraint({ async: false })
class IsNotSiblingOfConstraint implements ValidatorConstraintInterface {
validate(value: any, args: ValidationArguments) {
if (validator.isDefined(value)) {
return this.getFailedConstraints(args).length === 0
}
return true;
}
defaultMessage(args: ValidationArguments) {
return `${args.property} cannot exist alongside the following defined properties: ${this.getFailedConstraints(args).join(', ')}`
}
getFailedConstraints(args: ValidationArguments) {
return args.constraints.filter((prop) => validator.isDefined(args.object[prop]))
}
}
// Create Decorator for the constraint that was just created
function IsNotSiblingOf(props: string[], validationOptions?: ValidationOptions) {
return function (object: Object, propertyName: string) {
registerDecorator({
target: object.constructor,
propertyName: propertyName,
options: validationOptions,
constraints: props,
validator: IsNotSiblingOfConstraint
});
};
}
// Helper function for determining if a prop should be validated
function incompatibleSiblingsNotPresent(incompatibleSiblings: string[]) {
return function (o, v) {
return Boolean(
validator.isDefined(v) || // Validate if prop has value
incompatibleSiblings.every((prop) => !validator.isDefined(o[prop])) // Validate if all incompatible siblings are not defined
)
}
}
Your class
class UpdateUserDTO {
@IsString()
@IsNotSiblingOf(['deleted'])
@ValidateIf(incompatibleSiblingsNotPresent(['deleted']))
readonly status: string;
@IsBoolean()
@IsNotSiblingOf(['status'])
@ValidateIf(incompatibleSiblingsNotPresent(['status']))
readonly deleted: boolean;
@IsString()
readonly name: string;
}
_Note: there are definitely some improvements that can be made to this, but as a quick example it should get the job done._
If you wanted to you could wrap these two decorators in a decorator to make it a one line validation definition.
Extending @halcarleton 's work above as suggested to combine the two decorators, the following works for me:
export function IncompatableWith(incompatibleSiblings: string[]) {
const notSibling = IsNotSiblingOf(incompatibleSiblings);
const validateIf = ValidateIf(
incompatibleSiblingsNotPresent(incompatibleSiblings)
);
return function(target: any, key: string) {
notSibling(target, key);
validateIf(target, key);
};
}
class UpdateUserDTO {
@IncompatableWith(['deleted'])
@IsString()
readonly status: string;
@IncompatableWith(['status'])
@IsBoolean()
readonly deleted: boolean;
@IsString()
readonly name: string;
Naive question @halcarleton but where does the validator in validator.isDefined(value) come from? I don't see that function in this validator package: https://github.com/validatorjs/validator.js. Is there another?
@piersmacdonald validator.isDefined(value) is part of this package: https://github.com/typestack/class-validator/blob/develop/src/decorator/common/IsDefined.ts
Most helpful comment
Extending @halcarleton 's work above as suggested to combine the two decorators, the following works for me: