ur truly friend
ur truly friend

Reputation: 553

Regex to validate a number while typing

I want to validate a number, while user starts typing in the input field. I tried with the following regular expression it's not working fully.

/^\d+(?:\.\d{1,3})?$/

It's satisfied following cases as I expected. 120 ---> True, 120.2 ---> True, 120.123 --> True 120g --> False

It's not satisfying a single case as I expected.

120. --> returning false --> But I am expecting true.

can anyone help me.

Thanks

Upvotes: 0

Views: 744

Answers (2)

KooiInc
KooiInc

Reputation: 122986

Most of the time it's a bad idea to use RegExp for validation of number values. Use <input type="number">. See my answer here for validation, the snippet from that answer:

(() => {
  const inputElement = document.querySelector("#ex2");
  const report = document.querySelector("#report");
  const bttn = document.querySelector("button");
  const getAction = cando => cando ? "removeAttribute" : "setAttribute";
  const checkVal = val => val
      && val >= +inputElement.getAttribute("min")  
      && val <= +inputElement.getAttribute("max");
  const messages = {
    cando: "Ok to submit",
    noValue: "Waiting for input (1.400,00 - 12.000,00)",
    invalid: "Value should be from 1.400,00 up to 12.000,00"
  };
  
  inputElement.focus();
  checkValue();

  function checkValue() {
    const val = inputElement.value;
    const cando = checkVal(val);
    report.innerHTML = !val 
      ? messages.noValue
      : cando
        ? messages.cando
        : messages.invalid;
    bttn[getAction(cando)]("disabled", true);
    return setTimeout(checkValue, 200);
  }
})();
<input id="ex2" 
  type="number"
  min="1400" 
  max="12000"
  step="0.01"/>

<button disabled>submit</button> <span id="report"></span>

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 371178

You need the digits following the possible . to be optional, in case the user just typed the period but hasn't typed further yet. Use \d{0,3} rather than \d{1,3}:

console.log(/^\d+(?:\.\d{0,3})?$/.test('120.'));

If you want to verify that there's no trailing period, do so after the user indicates that they're done typing, such as on form submit, in which case you can use your original regex.

Upvotes: 4

Related Questions