Enforcing leading zero in two-digit input? #859
Unanswered
bdurham-simpleclosure
asked this question in
Q&A
Replies: 1 comment
-
This is what I’ve landed on, but I still wonder if there is something simpler: import { NumberFormatBase } from "react-number-format";
function DateInput({ max = 12, onChange, prefix = "0" }) {
const format = (val) => {
let formatted = "";
const valAsNumber = Number(val);
const maxChars = max.toString().length;
if (val === "" || valAsNumber === 0) return "";
if (val.length === 1) {
formatted = `${prefix}${val}`;
} else if (valAsNumber > max && val.substring(0, 1) !== prefix) {
return `${max}`;
} else if (valAsNumber > max && val.substring(0, 1) === prefix) {
return val.substring(0, maxChars);
} else if (valAsNumber <= max && val.substring(0, 1) === prefix) {
return `${valAsNumber}`;
} else if (valAsNumber > max) {
return `${max}`;
} else if (val.length > maxChars) {
return val.substring(0, maxChars);
} else {
formatted = val;
}
return formatted;
};
return <NumberFormatBase format={format} onChange={onChange} />;
}
export default function App() {
return (
<main>
<div>Month</div>
<DateInput max={12} />
<br />
<br />
<div>Year</div>
<DateInput max={new Date().getFullYear()} prefix="" />
</main>
);
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I’m just creating an input where the user can enter a month. The value is required to have a leading zero if the month is < 10. If 10 or higher the value should be the number entered. The closest I’ve gotten is with this:
But of course you can only enter one digit here. The leading zero is persistent.
Is there a way to pull this off easily? I feel like I’m missing something obvious.
Beta Was this translation helpful? Give feedback.
All reactions