Skip to content Skip to sidebar Skip to footer

Is There Any Way To Prevent Input Type=“number” Getting More Than One Dot Values?

I want to get only decimal values like 1.5,0.56 etc. but its allowing more than one dot. is there any way to prevent it

Solution 1:

You can use pattern attribute:

 <inputtype="text" pattern="[0-9]+([\.,][0-9]+)?">

It will allow patterns with a single dot, or even a comma (european decimals for example). To remove the comma, should be:

 <inputtype="text" pattern="[0-9]+([\.][0-9]+)?">

Solution 2:

Originally shared here

You can find very detailed explainations in this Codepen

This solution is simple and will only allow one dot in the number field. It doesn't prevent from clicking back in the number and adding numbers before the ".". It doesn't prevent from executing browser keyboard shortcuts like refresh, copy and pasting (as long as the pasted value is a valid number) and others. It will allow to add "." withing the body of the number, but will remove any exceeding floats over the set limit.

The only behavior that I still can't prevent is if you press the dot key at the end of the input repeatedly, the dot will blink on and off. This happens because a typed value of "13." is a valid number and returns "13" and a typed value of "13.." is not and returns "". In my solution, if a value returns "" without the press of backspace or delete, it gets rolled back to the last valid value, wich is "13", obtained from the typed value "13.".

I've tried solutions where if a dot was pressed once, it was prevented to be triggered a second time, but every time I managed to get stuck with pressing the dot right after an already existing dot followed by nothing and then get stuck with not being able to type a dot unless I pressed any other key first.

I think the blinking on multiple press is the best solution for ther's no way a user would type a dot and nothing happens.

let lastValidInputValue;
let selectedDot = false;


constonKeypress = (e) => {
  if (e.key === "." && e.target.value.indexOf(".") !== -1 && !selectedDot) e.preventDefault();
  selectedDot = false;

  if (e.key === "e") e.preventDefault();
};


constonInput = (e) => {
  if (
    e.target.value.indexOf(".") < e.target.value.length - e.target.getAttribute("data-toFixed") - 1 &&
    e.target.value.indexOf(".") !== -1
  ) {
    let newValue;
    newValue = e.target.value.slice(
      0,
      e.target.value.indexOf(".") +
        parseInt(e.target.getAttribute("data-toFixed")) +
        1
    );
    newValue = parseFloat(newValue);
    e.target.value = newValue;
  }
  if (e.target.value !== "") {
    lastValidInputValue = e.target.value;
  } elseif (e.inputType.match(/delete/g)) {
    lastValidInputValue = "";
  } else {
    e.target.value = lastValidInputValue;
  }
};

 constonSelect = (e) => {
   if(window.getSelection().toString().indexOf(".") > -1) selectedDot = true;
 }
<inputtype="number"id="myNumber"name="myNumber"data-toFixed="2"step="any"onkeypress="onKeypress(event)"oninput="onInput(event)"onselect="onSelect(event)">

Solution 3:

I know, it's old one. I'm not sure that you need overcomplicate solution with checking indexOf and so on...

What I needed (and what I show here) is to limit user to input (pos/negative) numbers with at most 2 decimals, no letters, no double dots or other stuff.

<inputtype="text"value="0"/>
$("input").on('input', function(e){
    let {value} = e.target;
    let processedValue = value
            .replace(/[^\d.\-]/, "")
            .replace(/^([\-]{0,1})(\d*)((\.\d{0,2}){0,1})(.*)$/g, "$1$2$3")
    $("input").val(processedValue);
  });

My regex could be a bit rough but it works. In short it's cleaning anything that is not number and dot, and then takes only first part with dot.

Solution 4:

I've simplest code to prevent multiple dots and it's also prevent some other invalid values:

$('input[type=number]').on('keydown', function (e) {
    var keyCode = e.keyCode || e.which;

    if ((keyCode == 190 || keyCode == 110) && (e.currentTarget.validity) && (!e.currentTarget.validity.valid))
    {
        e.preventDefault();
        returnfalse;
    }
});

Solution 5:

You could use JavaScript to capture any change in the input value, and check whether the inputAsNumber property is still a valid number. If not, you could revert to the previous value:

restoreData = {};

inp.oninput = preventTwoDots;
restoreData['inp'] = inp.value;

functionpreventTwoDots() {
    if (isNaN(this.valueAsNumber) && this.selectionStart) {
        this.value = restoreData['inp'];
    }
    restoreData['inp'] = this.value;
}
<inputtype="number"id="inp">

The extra check on selectionStart makes sure that you can still remove all digits: an empty input is considered an invalid number, but it would be strange to not be able to delete the last character from the input.

Remarks

Although this is what you asked for in your question, please note that blocking user input is not particularly user-friendly. Browsers give visual clues when the input is not valid (on committing the value, for instance when you leave the input field), which generally is how it should be done. You don't want people to think their keyboard is failing, or let them think the clipboard is empty because their copy/paste is "not working".

Post a Comment for "Is There Any Way To Prevent Input Type=“number” Getting More Than One Dot Values?"