-1

I'am trying to allow following pattern for a single html input box with javascript regex

  • -int (aka any minus number so long it not followed by a zero and is in the first position)
  • 0 (a single zero is allowed)
  • int (is allowed)

I use this function the remove anything that doesn't match it

    $('.dointcheck').live('keyup',
        function () {
            $(this).val($(this).val().replace((/^((?!:([1-9-]?[0-9])).)/g), ''));
            if ($(this).val().length == 0) {
                $(this).val(0);
            }
        }); 

which doesn't work. Other examples is:

  1. /[^-0-9]/g it removes any non valid chars but doesnt check if the minus is the beginning and is followed by a zero. It allows minus everywhere in the string
  2. (/^((?!:([1-9-]?[0-9])).)/g Don't allow none.
  3. [^1-9-]?[^0-9]* Allow all...

I think I'am missing something.. Any suggestions would be most appreciated..

2
  • .live() has been deprecated with v1.7 and removed in v1.9 Commented Apr 7, 2022 at 13:49
  • 2
    <input type="number" ... /> Commented Apr 7, 2022 at 13:50

2 Answers 2

1

You may try this regex

^(0).*|^(-?)([1-9]\d*)?.*|^.*

and replace it with $1$2$3 after input

document.querySelector('input').addEventListener('input', ({ target }) => target.value = target.value.replace(/^(0).*|^(-)?([1-9]\d*)?.*|^.*/g, '$1$2$3'));
<input />

It has three tests:

^(0).*               // if it starts with 0, discard everything after it
^(-)?([1-9]\d*)?.*   // otherwise it can only starts with a -, or any number that is not a 0. Then followed by other digits, then discard everything after it
^.*                  // if previous rules are not matched, discard everything

In short:

  • generally only -, 0-9 are allowed.
  • if you type a 0 first, nothing will be allowed after.
  • if you type a 1-9 first, only numbers are allowed after.
  • if you type a - first, only 1-9 is allowed next, then any digit is allowed after.
Sign up to request clarification or add additional context in comments.

1 Comment

This is was I needed and the explanation what everything does is extremly helpfull
1

I changed your regexp and made it a bit more modular and it worked fine.

function toValidNumber(int) {
  return (/^\s*[+-]?(\d+|\d*\.\d+|\d+\.\d*)([Ee][+-]?\d+)?\s*$/).test(int) ? int : 0;
}

$('.dointcheck').live('keyup',
  function () {
    $(this).val(toValidNumber($(this).val()));
  }); 

Orginal RegEXP in Stackoverflow

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.