Created
March 27, 2019 08:48
-
-
Save nienkedekker/89ebab64ec7d7c32b81ea2de05d676e3 to your computer and use it in GitHub Desktop.
Custom TypeScript decorator for plain objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { IsString, IsOptional } from 'class-validator'; | |
import IsPlainObject from '../isPlainObject.decorator'; | |
export class Dto { | |
@IsOptional() | |
@IsPlainObject() | |
readonly data?: object; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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