Skip to content

Commit

Permalink
fix(renderer): update the required validator to properly handle falsy…
Browse files Browse the repository at this point in the history
… numeric values
  • Loading branch information
Dave Malloy committed Sep 25, 2024
1 parent a3488fc commit 8ad3c55
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,34 @@ describe('New validators', () => {
expect(validatorMapper[validatorTypes.REQUIRED]()('Foo')).toBeUndefined();
});

it('should pass required validator if numeric truthy value', () => {
expect(validatorMapper[validatorTypes.REQUIRED]()(1)).toBeUndefined();
});

it('should pass required validator if numeric falsy value', () => {
expect(validatorMapper[validatorTypes.REQUIRED]()(0)).toBeUndefined();
});

it('should pass required validator if boolean true', () => {
expect(validatorMapper[validatorTypes.REQUIRED]()(true)).toBeUndefined();
});

it('should pass required validator if boolean false', () => {
expect(validatorMapper[validatorTypes.REQUIRED]()(false)).toBeUndefined();
});

it('should fail required validator', () => {
expect(validatorMapper[validatorTypes.REQUIRED]()()).toBe('Required');
});

it('should fail required validator if explictly null', () => {
expect(validatorMapper[validatorTypes.REQUIRED]()(null)).toBe('Required');
});

it('should fail required validator if explictly undefined', () => {
expect(validatorMapper[validatorTypes.REQUIRED]()(undefined)).toBe('Required');
});

it('should fail required validator if string of white spaces', () => {
expect(validatorMapper[validatorTypes.REQUIRED]()(' ')).toBe('Required');
});
Expand Down
13 changes: 11 additions & 2 deletions packages/react-form-renderer/src/validators/validator-functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,17 @@ import { memoize, prepare, prepareMsg, selectNum, isNumber, trunc } from '../com

export const required = memoize(({ message } = {}) => {
return prepare((value) => {
const cond = typeof value === 'string' ? !value.trim() : value && !isNaN(value.length) ? !value.length : !value;
if (cond) {
let failsValidation = true;

if (typeof value === 'string') {
failsValidation = !value.trim();
} else if (Array.isArray(value)) {
failsValidation = !value.length;
} else {
failsValidation = value === null || value === undefined;
}

if (failsValidation) {
return prepareMsg(message, 'required').defaultMessage;
}
});
Expand Down

0 comments on commit 8ad3c55

Please sign in to comment.