Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated the required validator to properly handle falsy numeric values #1485

Merged
merged 1 commit into from
Sep 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading