Skip to content

Commit

Permalink
Improve int validator readability
Browse files Browse the repository at this point in the history
  • Loading branch information
SoniaSanzV committed Oct 24, 2024
1 parent b30cb83 commit 8c156ce
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,12 @@ describe('isInteger', () => {
test('should return Validation function if value a string that can not be parsed to number', () => {
expect(validator('test')).toMatchObject({ message, code });
});

test('should return Validation function if value is boolean', () => {
expect(validator(false)).toMatchObject({ message, code });
});

test('should return undefined if value is empty', () => {
expect(validator('')).toBeUndefined();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,13 @@ export const isInteger =
(...args: Parameters<ValidationFunc>): ReturnType<ValidationFunc<any, ERROR_CODE>> => {
const [{ value }] = args;

if (value === '') {
return;
if (
value === '' ||
(typeof value === 'number' && Number.isInteger(value)) ||
(typeof value === 'string' && Number.isInteger(Number(value)))
) {
return undefined;
}

const numValue = typeof value === 'string' ? Number(value) : value;

return Number.isInteger(numValue) ? undefined : { message, code: 'ERR_NOT_INT_NUMBER' };
return { message, code: 'ERR_NOT_INT_NUMBER' };
};

0 comments on commit 8c156ce

Please sign in to comment.