简体   繁体   中英

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.

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));
}

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.

使用此re:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM