Skip to content

Commit

Permalink
feat: enhance IsNotBlank validation to include numbers and handle nul…
Browse files Browse the repository at this point in the history
…l/undefined
  • Loading branch information
gabriel-logan committed Jan 24, 2025
1 parent 70e3210 commit 58e908e
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
21 changes: 20 additions & 1 deletion src/decorator/common/IsNotBlank.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,29 @@ import { buildMessage, ValidateBy } from './ValidateBy';

export const IS_NOT_BLANK = 'isNotBlank';

/**
* @param value The value to be checked
* @returns true if the value is not blank, false otherwise
*/
export function isNotBlank(value: unknown): boolean {
return !!value && typeof value === 'string' && value.trim().length > 0;
if (value == null) return false; // Verify if the value is null or undefined

if (typeof value === 'string') return value.trim().length > 0;

if (typeof value === 'number') return !isNaN(value);

return false; // Any other type is considered invalid
}

/**
* @param validationOptions The validation options
* @returns {PropertyDecorator}
*
* @description
* The decorator checks if the value is not blank
* @description
* The value is considered blank if it is null, undefined, empty string or NaN
*/
export function IsNotBlank(validationOptions?: ValidationOptions): PropertyDecorator {
return ValidateBy(
{
Expand Down
6 changes: 3 additions & 3 deletions test/functional/validation-functions-and-decorators.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -424,7 +424,7 @@ describe('IsEmpty', () => {
});

describe('IsNotEmpty', () => {
const validValues = ['a', 'abc', ' '];
const validValues = ['a', 'abc', ' ', 0, 1];
const invalidValues = ['', undefined, null];

class MyClass {
Expand Down Expand Up @@ -456,8 +456,8 @@ describe('IsNotEmpty', () => {
});

describe('IsNotBlank', () => {
const validValues = ['a', 'abc'];
const invalidValues = ['', undefined, null, ' '];
const validValues = ['a', 'abc', 0, 1];
const invalidValues = ['', undefined, null, ' ', new Object()];

class MyClass {
@IsNotBlank()
Expand Down

0 comments on commit 58e908e

Please sign in to comment.