Skip to content

Validators

ArteMerlow edited this page May 28, 2025 · 1 revision

Validators

ModularORM has built-in support for validators for DTOs, provided in the form of ready-made decorators and builders.

To use decorators, first create a DTO

class LogsDTO {
    
    @Result()
    public id!: number;
    
    @Result('date')
    public logDate!: Date;
    
    @Result('user')
    public nickname!: string;
    
}

And now you can add validators to them

class LogsDTO {
    
    @Result()
    @IsNumber()
    public id!: number;
    
    @Result('date')
    @IsDate()
    public logDate!: Date;
    
    @Result('user')
    @IsSafeString()
    @Min(3)
    @Max(32)
    public nickname!: string;
    
}

Next, you need to choose how validation will occur. You can either write validation errors to Set:

class LogsDTO implements Validate {
    
    @Result()
    @IsNumber()
    public id!: number;
    
    @Result('date')
    @IsDate()
    public logDate!: Date;
    
    @Result('user')
    @IsSafeString()
    @Min(3)
    @Max(32)
    public nickname!: string;
    
    public validateErrors: Set<string> = new Set();
}

Or throw exceptions in case of validation errors. To do this, configure the ORM launch:

await ModularORM.getInstance().start({
    // ...
    validationErrors: true
})

And this way the methods will throw an exception on validation errors that you can catch.

const users : LogsDTO[] = await logsRepository.find().catch(
    (e) => { console.error(e) }
);

And with returnsNullWhenErrors you can return null or an empty array

await ModularORM.getInstance().start({
    // ...
    validationErrors: true,
    returnsNullWhenErrors: true
})

// If errors occur, it will be null
const users : LogsDTO | null = await logsRepository.findOne();

How to create your own validators?

There is a ValidatorFactory class for this

export const IsObject = () => ValidatorFactory.createValidator(
    (value: any, column: string) => {
        return value instanceof UrObj
    },
    "Error!"
)

The method takes a function, which in turn takes 2 arguments: the value returned from the database and the name of this column. The passed function must return boolean. The second argument is the string with the error

Here is list of default (build-in) validators

Name Params Description Error message
@IsIntegerBased - Checks that the provided value is a number or can be converted to one. Must be a valid number
@IsBooleanBased - Checks that the provided value is a boolean or can be converted to one. Must be a boolean or 0/1
@IsAID - Checks that the value is a number and that it is greater than zero. Must be a number greater than 0
@IsString - Checks that value is a string Must be a string
@IsNumber - Checks that value is a number Must be a number
@IsBoolean - Checks that value is a boolean Must be a boolean
@IsJSON - Checks that the value is an object ({}), not an array or null. Must be a JSON object
@IsUUID - Checks that value is a string and that length it is less than or equal to 64. Must be a string with length <= 64
@IsLongVarchar - Checks that value is a string and that length it is less than or equal to 255. Must be a string with length <= 255
@IsUserField - Checks that value is a string and that length it is less than or equal to 500. Must be a string with length <= 500'
@IsDate - Checks that value is a Date object Must be a valid Date
@IsInArray String REST array Checks that the value is in the array passed to the annotation. Value must be one of [${args.join(', ')}]
@Min number Checks that the number (or the length of the string, if a string is provided) is greater than the provided value. Must be greater than or equal to ${min}
@Max number Checks that the number (or the length of the string, if a string is provided) is less than the provided value. Must be less than or equal to ${max}
@IsNotNull - Checks that value is not null or undefined. Must not be null or undefined
@IsNullable - Checks that value is null or undefined. Must be a null or undefined
@Equals any Compares the value with the value passed to it. Must be equal to ${checkVal}
@NotEquals any Checks that the value is not equal to the provided value. Must not be equal to ${checkVal}
@IsNotEmptyArray - Checks that the value is an array and that it is not empty. Must be a non-empty array
@IsEmptyArray - Checks that the value is an array and that it is empty. Must be an empty array
@IsPositive - Checks that the number is greater than zero. Must be a positive number
@IsNegative - Checks that the number is less than 1. Must be a negative number
@IsArray - Checks that value is a array Must be an array
@IsSafeString - Checks that value is a string and that it contains only allowed characters: A-Z a-z А-Я а-я 0-9 ! @ # $ % ^ & * ( ) _ + = [ ] { } | ; : ' " , . < > ? \ / String contains invalid characters. Allowed characters: English and Russian letters, digits, and safe symbols (!@#$%^&*()_+=[]{}|;:'",.<>?/-).

Clone this wiki locally