Thursday, October 24, 2013

javascript to allow textbox decimal value upto 2 places only

Below is the function which will validate the text box value and will only allow to enter decimal upto 2 places:

Method 1:

Javascript Function:

function checkDecimal(el){
 var ex = /^[0-9]+\.?[0-2]*$/;
 if(ex.test(el.value)==false){
     alert('Decimal Value upto 2 places allowed !');
     el.value = ''; 
  }
}


In textbox properties add onblur and call above javascript function:

<asp:TextBox runat="server" Width="180px" ID="textbox1" onblur="checkDecimal(this);" />


Method 2:

Javascript Function:

function onlyDotsAndNumbers(txt, event) {
    var charCode = (event.which) ? event.which : event.keyCode
    if (charCode == 46) {
        if (txt.value.indexOf(".") < 0)
            return true;
        else
            return false;
    }

    if (txt.value.indexOf(".") > 0) {
        var txtlen = txt.value.length;
        var dotpos = txt.value.indexOf(".");
        if ((txtlen - dotpos) > 2)
            return false;
    }

    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

aspx page:

<asp:TextBox runat="server" Width="180px" ID="textbox1" onkeypress="return onlyDotsAndNumbers(this,event);" />

No comments:

Post a Comment