0

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}>
Deep Kakkar
  • 5,831
  • 4
  • 39
  • 75
  • *the user should be able to enter decimal as well as negative numbers*. How can you type `0.1` without typing leading `0` first? – Hao Wu Jan 31 '23 at 05:42

5 Answers5

0

You can use regex to remove zeros from beginning: /^0+/

In your case:

onChange = (e) => {
    const _removedZeros = e.target.value.replace(/^0+/, '')
    ///...
}
TENTACLE
  • 11
  • 4
0

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.)

bignose
  • 30,281
  • 14
  • 77
  • 110
0

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

Ali Sattarzadeh
  • 3,220
  • 1
  • 6
  • 20
0

As per your description, you can solve this by using the parseFloat() function. This function will remove the leading zeros and will convert the input value to a decimal/fractional number. The code should be like this:

const onChange = (event) => {
  const value = parseFloat(event.target.value);
  event.target.value = isNaN(value) ? '' : value;
};
  • This works fine for all cases expect when there is a decimal number and we try to delete it , the cursor comes to the starting after deleting the decimal point. For eg 100.123 then after deleting the decimal places the cursor comes to the start of 100 – amit singh Jan 31 '23 at 08:45
  • So, what do you want? Is the dot supposed to be there? – Jahidul Islam Feb 02 '23 at 11:10
0

something like this?

foo.oninput = (e) => {
  const value = foo.value;

  let [_, sign, integer, decimals] = value.replace(/[^\d\.\-]/g, "") // invalid characters
    .replace(/(\..*?)\./g, "$1")  // multiple dots
    .replace(/(.+)-/g, "$1")      // invalid signs
    .match(/^(-?)(.*?)((?:\.\d*)?)$/);

  let pos = foo.selectionStart - 1;
  if(!integer && decimals) pos += 2;

  // don't convert an empty string into a 0, 
  // unless there are decimal places following
  if(integer || decimals) {
    integer = +integer;
  }
  
  const formatted = sign + integer + decimals;
  
  if(formatted !== value) {
    foo.value = formatted;
    foo.setSelectionRange(pos, pos);
  }
}
<input type="text" id="foo" />
Thomas
  • 11,958
  • 1
  • 14
  • 23
  • You could simply use the `Number` function followed by `.ToString()` – Salman A Jan 31 '23 at 07:06
  • @SalmanA `Number` would mess up a lot of inputs on the way to the value you're trying to input. Like how do you get from `""` over `"-"` to `"-5"` when `Number("") === 0` and `Number("-") is NaN)`. Or how do you input `1.05` when both `Number("1.")` and `Number("1.0")` are converted back to `1`. Your suggestion works fine `onblur` but not `onchange` or `oninput`. – Thomas Jan 31 '23 at 07:10
  • OP mentioned using `onChange` method, not `onInput`. I'll ask for clarification. – Salman A Jan 31 '23 at 07:13
  • 1
    @SalmanA afaik react reroutes `onInput` to `onChange` because `oninput` behaves how one would expect of `onchange`. In the browser `oninput` is preferred for such updates, because `onchange` may not fire on every change (counter-intuitive, but true). See https://stackoverflow.com/a/65726504/6567275 on the differences between the two. – Thomas Jan 31 '23 at 07:18
  • @Thomas thanks for your answer , it works for all cases , but I am not able to understand completely what you have done. It would be really helpful if you could elaborate your answer please. – amit singh Jan 31 '23 at 09:34