Created
December 27, 2018 22:53
-
-
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.
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 {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.`; | |
} | |
} |
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 {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.`; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: