skip to Main Content

I want to forbiden to write more that one dot, as well i want to forbiden to write more that one comma

if there is already an dot (.) should not allow to write other dot(.) or comma (,) and viceversa

i have this example:

function isNumberKey(evt, obj) {
  if (evt.target.selectionStart === 0 && (evt.keyCode == 46)) return false;
  var charCode = (evt.which) ? evt.which : evt.keyCode
  var value = obj.value;
  var dotcontains = value.indexOf(".") != -1;
  var commacontains = value.indexOf(",") != -1;
  if ((value.length == 0) && (event.keyCode == 46)) return false
  if (dotcontains || commacontains)
    if (charCode == 46 || charCode == 44) return false;

  if (charCode == 46 || charCode == 44) return true;
  if (charCode > 31 && (charCode < 48 || charCode > 57))
    return false;
  return true;
}
<INPUT TYPE="TEXT" VALUE="0" onkeypress="return isNumberKey(event,this)">

that is working but i need to do that with regex

i was trying with this regex:

/^[0-9]+(?:.[0-9]+)*$/

it should work like

<input type="number" />

2

Answers


  1. I agree a regex is a simpler way to accomplish this, and your regex seems to work, you just need it to be tested against the value. The problem is that if something like 0.4 is OK, as you type it out it won’t allow you to type the . so you can never get to that point!

    Here is my suggestion: instead of preventing the user from typing characters, just mark the field as invalid instead.

    I also recommend using an eventListener instead of the HTML attributes, since you can apply the same thing to multiple elements at once.

    [...document.querySelectorAll('.validate-numbers')]
      .forEach(function(element) {
        element.addEventListener('keyup', function() {
          const result = /^[0-9]+(?:.[0-9]+)*$/.test(this.value);
          this.classList.toggle('invalid', !result);
        });
      });
    .invalid {
      border-color: #FFFFFF;
      background-color: #FFCCCC;
    }
    <input type="text" value="0" class="validate-numbers">
    <input type="text" value="0" class="validate-numbers">
    <input type="text" value="0" class="validate-numbers">
    Login or Signup to reply.
  2. You may try this regex

    [^d.,]|(^d*[.,]d*).*
    

    and replace it with $1.

    Basically it only allows numeric characters, , and ., and it only allows one , or . to be present, anything other than those will be replaced to empty on the fly.


    Edit

    According to the added information in comments, to only allow maximum 3 fraction digits, you may change the regex a little bit:

    [^d.,]|(^d*[.,]d{0,3}).*
    
    const $input = document.querySelector('input');
    
    $input.addEventListener('input', () => {
      $input.value = $input.value.replace(/[^d.,]|(^d*[.,]d{0,3}).*/g, '$1');
    });
    <input />
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search