Skip to content

Instantly share code, notes, and snippets.

@nienkedekker
Created March 27, 2019 08:48
Show Gist options
  • Save nienkedekker/89ebab64ec7d7c32b81ea2de05d676e3 to your computer and use it in GitHub Desktop.
Save nienkedekker/89ebab64ec7d7c32b81ea2de05d676e3 to your computer and use it in GitHub Desktop.
Custom TypeScript decorator for plain objects
import { IsString, IsOptional } from 'class-validator';
import IsPlainObject from '../isPlainObject.decorator';
export class Dto {
@IsOptional()
@IsPlainObject()
readonly data?: object;
}
import {registerDecorator, ValidationOptions, ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments} from 'class-validator';
@ValidatorConstraint({ async: true })
export class ValidateObject implements ValidatorConstraintInterface {
validate(data: object, args: ValidationArguments) {
return data.constructor === Object;
}
}
export default function IsPlainObject(validationOptions?: ValidationOptions) {
return (object: object, propertyName: string) => {
registerDecorator({
target: object.constructor,
propertyName,
options: validationOptions,
constraints: [],
validator: ValidateObject,
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment