Рет қаралды 105
Unlock the full potential of data validation in your NestJS applications by learning how to create custom decorators! In this detailed tutorial, we delve into the power of the class-validator library and show you how to craft a versatile IsNumber decorator. This custom decorator not only checks if a value is a number but also lets you specify minimum and maximum values for enhanced data integrity.
import { applyDecorators } from '@nestjs/common';
import { IsNumber as IsNumberBase, Min, Max } from 'class-validator';
import { DEFAULT_MIN, DEFAULT_MAX } from '../constants/number-fields.constants';
type TIsNumberOptions = {
min?: number;
max?: number;
};
export default function IsNumber(options?: TIsNumberOptions) {
const { min = DEFAULT_MIN, max = DEFAULT_MAX } = options || {};
return applyDecorators(IsNumberBase(), Min(min), Max(max));
}