Monday, 20 October 2014

Decimal / Floating point number validation using javascript / jQuery (regular expression)

To validate any decimal number

    function validateDecimal(value)    {
        var RE = /^\d*\.?\d*$/;
        if(RE.test(value)){
           return true;
        }else{
           return false;
        }
    }

Eg: 54     -> true
     1.235  -> true
     12.258 -> true
     1.2.5  -> false
     sdf123 -> false

To validate decimal number with two digit precision

function validateDecimal(value)    {
    var RE = /^\d*(\.\d{1})?\d{0,1}$/;
    if(RE.test(value)){
       return true;
    }else{
       return false;
    }
}

Eg: 54     -> true
    5.2       -> true
    1.23   -> true
    155.89 -> true
    12.258 -> false
    1.2.5  -> false
    sdf123 -> false


General form of regular expression for decimal a number

    ^\d{0,M}(\.\d{1})?\d{0,N}$

M = at most number of digits before decimal point.
N = (n-1); n = at most number of digits after decimal point.

0 comments:

Post a Comment