I have added <input type="number" value={value} onChange={onChange}> to a form and am checking the format of the input using a simplified onChange function as illustrated in the following component:
export function App() {
const [value, setValue] = useState("");
const onChange = (event) => {
console.log("onChange called", event.target.value);
setValue(event.target.value);
};
return <input type="number" value={value} onChange={onChange} />;
}
I would like restrict the value of the input to only be integers using validation in the onChange function.
However, before I can add the validation, I noticed that when a user enters a valid non-integer number input, such as ., e or E, the value of the input is not passed to the onChange function, and hence I'm not able to perform my validation.
Below is a codesandbox that can be used to reproduce the issue.
What is the best way to add validation to an input field to ensure that the input is a whole number?
type='number'as an attribute in your input field. HTML does that for you. The browser solves that for you. Why do you need to validate yourself?