I have an input which can't have more than 2 decimal places. Also I have validation, which doesn't work properly for numbers with lots of zeros.
export default function App() {
const isValidAmount = (amount) => /^$|^\d+\.?\d{0,2}$/.test(String(amount));
return (
<div>
<Formik initialValues={{ decimalNumber: "" }}>
{({ handleChange }) => (
<Field
className="input"
type="number"
name="decimalNumber"
placeholder="Decimal Number"
component={TextField}
InputProps={{
onChange: (e) => {
if (!isValidAmount(e.target.value)) return;
handleChange(e);
}
}}
/>
)}
</Formik>
</div>
);
}
Can you please explain: What is going on?
Use the HTML step attribute to limit the allowable numbers. In this case you want to limit to hundredths:
<Field
/* ... */
step="0.01"
/>