Skip to content

Commit

Permalink
Merge pull request #37 from iway1/bug/number-field-0-and-negative
Browse files Browse the repository at this point in the history
Number fields now allow leading minus sign and 0
  • Loading branch information
iway1 authored Jan 14, 2023
2 parents 3ee4bdf + 90df6ea commit 3dfc065
Showing 1 changed file with 6 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,25 +22,18 @@ export function NumberField({
});

function onChange(value: string) {
if (value == "") {
setStringValue("");
return;
}
const numberValue = parseFloat(value);
if (isNaN(numberValue)) return;
setStringValue(numberValue + (value[value.length - 1] == "." ? "." : ""));
setStringValue(value.replace(/[^\d.-]/g, ""));
}

useEffect(() => {
// Not sure how else to do this while still allowing users to input a decimal point
const parsed = parseFloat(stringValue);
if (isNaN(parsed)) {
field.onChange(undefined);
return;
}
field.onChange(parseFloat(stringValue));
}, [stringValue]);

// ¯\_(ツ)_/¯
useEffect(() => {
if (!field.value) setStringValue("");
}, [field.value]);

return (
<BaseTextField
onChange={onChange}
Expand Down

0 comments on commit 3dfc065

Please sign in to comment.