Skip to content

Commit

Permalink
validators for TextField
Browse files Browse the repository at this point in the history
  • Loading branch information
vkoktashev committed Aug 12, 2024
1 parent feb7724 commit 61734c1
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion src/infrastructure/decorators/fields/TextField.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
import {applyDecorators} from '@nestjs/common';
import {Column} from '@steroidsjs/typeorm';
import {toInteger as _toInteger} from 'lodash';
import {IsOptional, IsString, MaxLength, MinLength} from 'class-validator';
import {BaseField, IBaseFieldOptions} from './BaseField';

export function TextField(options: IBaseFieldOptions = {}) {
export interface ITextFieldOptions extends IBaseFieldOptions {
isStringConstraintMessage?: string,
minConstraintMessage?: string,
maxConstraintMessage?: string,
}

export function TextField(options: ITextFieldOptions = {}) {
return applyDecorators(
BaseField(options, {
decoratorName: 'TextField',
Expand All @@ -15,5 +23,19 @@ export function TextField(options: IBaseFieldOptions = {}) {
default: options.defaultValue,
nullable: options.nullable,
}),
IsString({
each: options.isArray,
message: options.isStringConstraintMessage || 'Должна быть строка',
}),
!options.required && IsOptional(),
typeof options.min === 'number' && MinLength(options.min, {
message: options.minConstraintMessage,
each: options.isArray,
}),
typeof options.max === 'number' && MaxLength(_toInteger(options.max), {
message: options.maxConstraintMessage,
each: options.isArray,
}),

);
}

0 comments on commit 61734c1

Please sign in to comment.