Skip to content

Instantly share code, notes, and snippets.

@marvinrabe
Created December 27, 2018 22:53
Show Gist options
  • Save marvinrabe/e314829fa0aacfb23e6615a9c3c7e679 to your computer and use it in GitHub Desktop.
Save marvinrabe/e314829fa0aacfb23e6615a9c3c7e679 to your computer and use it in GitHub Desktop.
Validates if value exists or is unique in database. Using class-validator and typorm.
import {getRepository} from 'typeorm';
import {ValidationArguments, ValidatorConstraint, ValidatorConstraintInterface} from "class-validator";
@ValidatorConstraint({name: "exists", async: true})
export class IsExisting implements ValidatorConstraintInterface {
async validate(value: any, args: ValidationArguments) {
return 0 !== await getRepository(args.constraints[0]).count({
where: {
[args.constraints[1]]: value
}
});
}
defaultMessage(args: ValidationArguments) {
return `The selected ${args.property} is invalid.`;
}
}
import {getRepository} from 'typeorm';
import {ValidationArguments, ValidatorConstraint, ValidatorConstraintInterface} from "class-validator";
@ValidatorConstraint({name: "unique", async: true})
export class IsUnique implements ValidatorConstraintInterface {
async validate(value: any, args: ValidationArguments) {
return 0 === await getRepository(args.constraints[0]).count({
where: {
[args.constraints[1]]: value
}
});
}
defaultMessage(args: ValidationArguments) {
return `The ${args.property} has already been taken.`;
}
}
@marvinrabe
Copy link
Author

Usage:

import {Validate} from 'class-validator';
import {IsUnique} from "../Constraints/IsUnique";
import {User} from "../Entities/User";

export class Registration {
    @Validate(IsUnique, [User, 'email'])
    email: string;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment