RMN
RMN

Reputation: 752

Regular Expression in Javascript for number with decimal

I want a regular expression for a textbox which allows only 3 digits and passes following criterias:

  1. Only digits (234 or 123) or
  2. Only one decimal at the end (55.1)
  3. Should not allow spaces
  4. If decimal is used then there should be a number after/before decimal as well (555. or 12. or .12 should not be allowed)

I have following RE which works partially:

/^\d{0,3}$|^\d{0,2}[\.]\d{1}$/

Any help in modifying this ?

Looks like problem is additional:

I am using the code at keypress. So it validates each pressed value at key press.

  if (window.event)    {
        knum = e.keyCode;
    }
    else if (e.which)    {
        knum = e.which;
    }
    kchar = String.fromCharCode(knum);
    numcheck = /^\d{0,3}$|^\d{0,2}[\.]\d{1}$/;

    alert(numcheck.test(kchar));

It returns false for any decimal key press. Even if I enter 55 and then try a decimal in middle to make it 5.5, ite returns false.

Upvotes: 0

Views: 5811

Answers (3)

aorcsik
aorcsik

Reputation: 15552

You need at least 1 digit, but 3 at most: \d{1,3}

OR

There have to be at least 1 but no more than 2 digits before and 1 after the decimal: \d{1,2}[.]\d

So these combined: /(^\d{1,3}$|^\d{1,2}[.]\d$)/

UPDATE:

You are testing the character which was added on the keypress event, not the full value of the input field. This would never have the expected result.

document.getElementById("yourfield").onkeyup = function(e) {

    // the event
    if (!e) e = window.event;

    // determine the target of the keyup event (the input field)
    var targ;
    if (e.target)
       targ = e.target;
    else if (e.srcElement)
       targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
       targ = targ.parentNode;

    // get the value
    kchar = targ.value;
    numcheck = /^\d{0,3}$|^\d{0,2}[\.]\d{1}$/;

    // test
    alert(numcheck.test(kchar));
}

Upvotes: 2

Igor Chubin
Igor Chubin

Reputation: 64623

Use this re:

/^\d{1,3}$|^\d{1,2}[.]\d$/

Upvotes: 0

Qsario
Qsario

Reputation: 1026

Try /^\d{1,3}|(\d{1,2}\.\d)$/?

Your character class should not escape the period, so it should be [.], though I prefer to write just \. because it's a waste to create a class for one character. Similarly, \d{1} is redundant when \d means exactly the same thing. I'm also assuming that you don't want to allow an empty text box, either, so I wrote something that allows 1-3 digits, or 1-2 digits, a period, then one more digit. If that's wrong, you can change the range on that first \d back to {0,3}, which will allow for a text box containing nothing at all.

Upvotes: 1

Related Questions