Unique validation with Node.js class-validator

2019-10-03

This is about class-validator, nodejs.

https://github.com/typestack/class-validator

Installation

npm install class-validator --save

This is a validation library that is used annotations to set the validation rules in a model class properties.

It is easy to use this library with document. But Unique check was gotcha for me.

Unique validation with class-validator

For example Hoge class is the model for `hoge` table, the following is to check a email address unique.

import {
    validate,
    registerDecorator,
    ValidationOptions,
    ValidatorConstraint,
    ValidatorConstraintInterface,
    ValidationArguments
} from "class-validator";

export class Hoge {

	@Unique({
        message: "This email address is already in use"
    })
    public email: string | null = null;
}

@ValidatorConstraint({async: true})
export class UniqueConstraint implements ValidatorConstraintInterface {
    async validate(value: any, args: ValidationArguments) {
    	// get records that equal the `email` value from DB.
    	// If exist the `email` value in target table, return false. (unique validation error)
        return true
    }
}

export function Unique(validationOptions?: ValidationOptions) {
    return function (object: Object, propertyName: string) {
        registerDecorator({
            target: object.constructor,
            propertyName: propertyName,
            options: validationOptions,
            constraints: [],
            validator: UniqueConstraint
        });
    };
}

It can validate a value unique with “validate" method.

const hoge = new Hoge()
hoge.email = 'test@test.com' // already using email address
validate(hoge).then(errors => {
    // this email address is already in use
});