Problem/Motivation
js/jquery.deprecated.functions.js implements the helper as:
$.isNumeric = (obj) => {
return !Number.isNaN(parseFloat(obj)) && Number.isFinite(obj);
};
Number.isFinite() does not coerce its argument, so it is false for every
string. The polyfill therefore disagrees with the jQuery implementation it
replaces:
| Argument | jQuery 3.7.1 | This module |
|---|---|---|
'3' |
TRUE | FALSE |
'3.5' |
TRUE | FALSE |
'1e3' |
TRUE | FALSE |
3 |
TRUE | TRUE |
'', 'abc', null, [], NaN, Infinity |
FALSE | FALSE |
Numeric strings are the main reason callers reach for $.isNumeric() at all:
values read from attributes, and form elements are strings.
Code that guards a value with it silently takes the other branch — a wrong
number rather than an error, which is harder to notice than a missing function.
Found while preparing a Drupal 11 upgrade: jquery-bar-rating guards its
stored rating with $.isNumeric(), and the module is exactly what is supposed
to keep that library working on jQuery 4.
The other helpers in the file are fine — isArray, isFunction, isWindow,
type, trim, camelCase and nodeName were compared against native
jQuery 3.7.1 across 18 inputs and match.
Proposed resolution
Use the definition from jQuery itself: accept numbers and strings, and check
that the value survives numeric coercion.
$.isNumeric = (obj) => {
const type = $.type(obj);
return (
(type === 'number' || type === 'string') &&
!Number.isNaN(obj - parseFloat(obj))
);
};
Remaining tasks
- Review the patch.
The patch also fills in part of the existing @todo in
JqueryDeprecatedFunctionsJsTest::testDeprecatedJqueryFunctionsExistAtRuntime()
with eleven $.isNumeric() assertions covering numeric strings, plain numbers
and the falsy cases. They fail on 1.0.4 and pass with the fix.
User interface changes
None.
API changes
None — the helper starts behaving the way the jQuery API it restores is
documented to behave.
Data model changes
None
| Comment | File | Size | Author |
|---|---|---|---|
| jquery_deprecated_functions-isnumeric-numeric-strings.patch | 2.44 KB | alezu |
Issue fork jquery_deprecated_functions-3614835
Show commands
Start within a Git clone of the project using the version control instructions.
Or, if you do not have SSH keys set up on git.drupalcode.org:
Comments
Comment #2
danrodComment #3
danrodComment #5
danrodThanks for the fix @alezu , I applied the patch, it fixes the issue with the
$.isNumericimplementation and tests are passing, I'll merge this to the 1.0.x branch.Comment #6
danrodComment #8
danrodMerged, thanks !
Comment #10
danrod