I would like to allow numbers higher than 0 in an input field of a react app - javascript. I don't want to have 0
only if it's the first letter. For example 1, 5, 15, 20, 500, 1000005
would be allowed, but 0.5
not. I found this Regex online, however it blocks ALL 0's from being entered.
const [val, setVal] = useState("");
return (
<div className="App">
<input
value={val}
onChange={(e) => setVal(e.target.value.replace(/[^1-9]/g, ""))}
/>
</div>
);
CodePudding user response:
import React, { useState } from 'react';
export function App(props) {
const [val, setVal] = useState("");
return (
<div className="App">
<input
value={val}
onChange={(e) => {
e.target.value>=1 ? setVal(e.target.value): setVal("")
}}
/>
</div>
);
}
it will only set value greater then 0
CodePudding user response:
To enforce integers greater than 0 you can remove all non-digits, followed by removing leading zeros:
const [val, setVal] = useState("");
return (
<div className="App">
<input
value={val}
onChange={(e) => setVal(e.target.value.replace(/[^0-9]/g, '').replace(/^0 /, ''))}
/>
</div>
);