Skip to content

Commit a48da17

Browse files
authored
Merge pull request #1485 from malloy045/master
Updated the required validator to properly handle falsy numeric values
2 parents a3488fc + 8ad3c55 commit a48da17

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

packages/react-form-renderer/src/tests/validators/validators.test.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,34 @@ describe('New validators', () => {
1010
expect(validatorMapper[validatorTypes.REQUIRED]()('Foo')).toBeUndefined();
1111
});
1212

13+
it('should pass required validator if numeric truthy value', () => {
14+
expect(validatorMapper[validatorTypes.REQUIRED]()(1)).toBeUndefined();
15+
});
16+
17+
it('should pass required validator if numeric falsy value', () => {
18+
expect(validatorMapper[validatorTypes.REQUIRED]()(0)).toBeUndefined();
19+
});
20+
21+
it('should pass required validator if boolean true', () => {
22+
expect(validatorMapper[validatorTypes.REQUIRED]()(true)).toBeUndefined();
23+
});
24+
25+
it('should pass required validator if boolean false', () => {
26+
expect(validatorMapper[validatorTypes.REQUIRED]()(false)).toBeUndefined();
27+
});
28+
1329
it('should fail required validator', () => {
1430
expect(validatorMapper[validatorTypes.REQUIRED]()()).toBe('Required');
1531
});
1632

33+
it('should fail required validator if explictly null', () => {
34+
expect(validatorMapper[validatorTypes.REQUIRED]()(null)).toBe('Required');
35+
});
36+
37+
it('should fail required validator if explictly undefined', () => {
38+
expect(validatorMapper[validatorTypes.REQUIRED]()(undefined)).toBe('Required');
39+
});
40+
1741
it('should fail required validator if string of white spaces', () => {
1842
expect(validatorMapper[validatorTypes.REQUIRED]()(' ')).toBe('Required');
1943
});

packages/react-form-renderer/src/validators/validator-functions.js

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,17 @@ import { memoize, prepare, prepareMsg, selectNum, isNumber, trunc } from '../com
22

33
export const required = memoize(({ message } = {}) => {
44
return prepare((value) => {
5-
const cond = typeof value === 'string' ? !value.trim() : value && !isNaN(value.length) ? !value.length : !value;
6-
if (cond) {
5+
let failsValidation = true;
6+
7+
if (typeof value === 'string') {
8+
failsValidation = !value.trim();
9+
} else if (Array.isArray(value)) {
10+
failsValidation = !value.length;
11+
} else {
12+
failsValidation = value === null || value === undefined;
13+
}
14+
15+
if (failsValidation) {
716
return prepareMsg(message, 'required').defaultMessage;
817
}
918
});

0 commit comments

Comments
 (0)