I am a beginner in React JS. I have a use case in that I want to correct the number that a user enters in <input type='number>
field.
By default, a user can enter numbers with leading zeros like 0002 or -0042, etc.
I want to make it such that the leading zeros are removed when the user enters the number. Also, the user should be able to enter decimal as well as negative numbers. I have done it using onBlur
but I want to somehow do it onChange method itself.
onChange=()=>{ ... }
<input type = 'number' onChange={onChange}>
CodePudding user response:
I want to make it such that the leading zeros are removed when the user enters the number.
You can remove the leading zeros with String.replace
:
// ... code that obtains the user input in `inputText` ...
inputSanitisedText = inputText.replace(/^0 /, '')
(I am assuming you don't want to change the user's input while they're entering it. That would be very bad UI design.)
CodePudding user response:
You can use regex to remove zeros from beginning: /^0 /
In your case:
onChange = (e) => {
const _removedZeros = e.target.value.replace(/^0 /, '')
///...
}
CodePudding user response:
you can simply multiplied value to 1, like this :
const [value, setValue] = useState("");
<input
value={Boolean(value) ? value : ''}
type="number"
onChange={(e) => setValue(e.target.value * 1)}
/>
in this way user cannot type leading zeros