Skip to content

Instantly share code, notes, and snippets.

@LukeHackett
Created January 30, 2018 19:16
Show Gist options
  • Save LukeHackett/d789659b60d7f6d0322445b4a799e0b0 to your computer and use it in GitHub Desktop.
Save LukeHackett/d789659b60d7f6d0322445b4a799e0b0 to your computer and use it in GitHub Desktop.
import {registerDecorator, ValidationOptions, ValidationArguments, Validator} from "class-validator";
function IsBase64Image(mimeTypes: string[], validationOptions?: ValidationOptions) {
return function (object: Object, propertyName: string) {
registerDecorator({
name: "IsBase64Image",
target: object.constructor,
propertyName: propertyName,
constraints: [mimeTypes],
options: validationOptions,
validator: {
validate(base64: any, args: ValidationArguments) {
const [imageMimeTypes] = args.constraints;
const validator = new Validator();
// Ensure the image base64 string is a string
if (!validator.isString(base64) || validator.isEmpty(base64)) {
return false;
}
const mimeTypeRegex = /^data:([a-zA-z0-9]+\/[a-zA-z0-9]+)(;charset=[a-zA-z0-9]+)?;base64,/;
const mimeTypeMatch = base64.match(mimeTypeRegex);
// Valid Base64 Images should have matched in 3 groups
if (validator.isEmpty(mimeTypeMatch) || mimeTypeMatch.length !== 3) {
return false;
}
// Ensure the image mime type is an expected one
if(imageMimeTypes.indexOf(mimeTypeMatch[1]) === -1) {
return false;
}
// Ensure the remainder (after the mime type) is valid base64
const rawImage = base64.replace(mimeTypeMatch[0], '');
if (!validator.isBase64(rawImage)) {
return false
}
// Valid base64 encoded image
return true;
}
}
});
};
}
class MinMax<T> {
min?: T;
max?: T;
}
class ValidImageOptions {
height?: MinMax<number>;
width?: MinMax<number>;
size?: MinMax<number>;
}
function IsValidImage(validImageOptions: ValidImageOptions, validationOptions?: ValidationOptions) {
return function (object: Object, propertyName: string) {
registerDecorator({
name: "IsValidImage",
target: object.constructor,
propertyName: propertyName,
constraints: [validImageOptions],
options: validationOptions,
validator: {
validate(base64: any, args: ValidationArguments) {
const validator = new Validator();
const { width, height, size } = args.constraints[0];
console.log(width, height, size );
return true;
}
}
});
};
}
export default class HeroImage {
public readonly id: number;
public text: string;
// @IsBase64Image(['image/png', 'image/jpg'])
@IsValidImage({ height: {}, size: { min: 300 } })
public data: string = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment