Created
September 29, 2025 14:47
-
-
Save garzuze/3190f58e010b66df2c2b9092602f168f to your computer and use it in GitHub Desktop.
Not Blank custom validator for class-validator -> does not allow empty strings nor strings with empty characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
registerDecorator, | |
ValidationArguments, | |
ValidationOptions, | |
ValidatorConstraint, | |
ValidatorConstraintInterface, | |
} from 'class-validator'; | |
@ValidatorConstraint({ name: 'isNotBlank', async: false }) | |
export class IsNotBlankConstraint implements ValidatorConstraintInterface { | |
// biome-ignore lint/suspicious/noExplicitAny: <tem que ser any> | |
validate(value: any, _args: ValidationArguments) { | |
return typeof value === 'string' && value.trim().length > 0 && !value.trim().includes(' '); | |
} | |
defaultMessage(args: ValidationArguments) { | |
return `"${args.property}" can't be empty.`; | |
} | |
} | |
export function isNotBlank(_validationOptions?: ValidationOptions) { | |
// biome-ignore lint/complexity/noBannedTypes: <tem que ser> | |
return function (object: Object, propertyName: string) { | |
registerDecorator({ | |
target: object.constructor, | |
propertyName, | |
constraints: [], | |
options: {}, | |
validator: IsNotBlankConstraint, | |
}); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment