feature: allow validator on whole class
Description
I searched and didn't find a solution to create a validator for the whole class instead of only one property. For example if I have three fields 'headline', 'text' and 'media' and all are optional but I want to validate that whether one of them has been set. Found something here, but this looks way too complicated to me and requires much more code. And you have to assign a validator to every property. In Angular there is a possibility to assign a Validator not only to formControls but also to fromGroups. In the following example the validator is assigned to the whole form:
this.postForm = this.fb.group({
headline: this.fb.control(this.post.headline, {
validators: [Validators.maxLength(64)],
}),
text: this.fb.control(this.post.text, {
validators: [Validators.maxLength(1024)],
}),
media: this.fb.array([], {
})
}, { validators: this.atLeastOneRequiredValidator() });
private atLeastOneRequiredValidator = (): ValidatorFn => {
return (controlGroup: AbstractControl) => {
if (controlGroup.get('headline')?.value) {
return null;
}
if (controlGroup.get('text')?.value) {
return null;
}
if ((controlGroup.get('media') as FormArray).length) {
return null;
}
return {
atLeastOneRequired: 'Whether headline, text or media should exist'
}
};
};
Proposed solution
I want something like this, which would be more or less the Angular equivalent: (it's only a scratch) So I want the possibility to assign validators to the whole class instead of only to properties. For me this is a very very basic feature and I am wondering why it doesn't exist, or didn't I found it?
export function HeadlineTextOrMediaExists(validationOptions?: ValidationOptions) {
return function (object: Object, propertyName: string) {
registerDecorator({
name: 'HeadlineTextOrMediaExists',
target: object.constructor,
propertyName: propertyName,
options: validationOptions,
validator: {
validate(post: PostDto, args: ValidationArguments) {
if (post.headline || post.text || post.media?.length) {
return true;
}
return false;
},
defaultMessage(args: ValidationArguments) {
return 'Whether headline, text or media should exist';
}
},
});
};
}
@Validate(HeadlineTextOrMediaExists())
export class PostDto {
@IsString()
@IsOptional()
headline: string;
@IsString()
@IsOptional()
text: string;
@Type(() => PostMediaDto)
@IsOptional()
@ValidateNested()
media: PostMediaDto[];
}
Same as #269
any news about this feature?
Hi guys, I also have a similar need/use case. Initially I thought we would have the capability to set a custom "validate" method on the class that would be called by class-validator in case it's defined after validating decorators. This is a very simple and intuitive solution for this use case and actually for any validation which does not exists on decorator. (In my eyes doing custom decorators should be the last resource as the whole point of using this lib is to get validation with just few lines of code...)