Unique validation with Node.js class-validator

  • 19 May 2019
Post image

This is about class-validator, nodejs.

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


Installation class-validator

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 = '[email protected]' // already using email address
validate(hoge).then(errors => {
    // this email address is already in use
});

(Article migrated from another blog)

You May Also Like