SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Evangelist NokX's Avatar
    Join Date
    Feb 2003
    Location
    Knoxville, TN
    Posts
    501
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Restricting field to numbers and a decimal only

    this will work...

    var regex = /^\d*\.{0,1}\d+$/;
    if (regex.test(mystring)) {
    alert("good");
    } else {
    alert("bad");
    }

    however - i need the function to work on a key event so i'm going this route...

    function numbers_only(e) {
    var key;
    var char;
    var regex = /^\d*\.{0,1}\d+$/;
    if (window.event) {
    key = e.keyCode;
    } else if (e.which) {
    key = e.which;
    }
    char = String.fromCharCode(key);
    return regex.test(char);
    }

    it only allows me to punch in numbers - which is beautiful, but i need to input a decimal, as well. any suggestions?

  2. #2
    SitePoint Zealot
    Join Date
    Dec 2006
    Posts
    182
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Try:
    Code:
    var regex = /[0-9.-]/;
    I had to also change your variable "char" to something else, b/c it was giving me a parse error. I think "char" is used by JS

  3. #3
    doRighteousDeeds++
    Join Date
    Aug 2006
    Location
    تركيا Turkey Türkiye
    Posts
    266
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

  4. #4
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The trouble with just looking at one key is you could accept values like .5.6.5
    I'd look at the whole value on each keypress.

    Code:
    someinputelement.onkeypress=function(e){
        e=window.event? event.srcElement:e.target;
        var v=e.value;
        if(v && parseFloat(v)!=v) e.value= v.slice(0,-1);
    }


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •