Friday, 11 April 2014

Allow only One Decimal & Numerics Value in textbox in C# ASP.NET using JAVASCRIPT

Below is the function which will validate the text box value and will only allow one decimal and Numerics value in it.

Aspx Page:
<asp:TextBox ID="txtAmount" placeholder="Enter Amount Here" onkeypress="return onlyOneDotAndNumbers(this,event);" runat="server"></asp:TextBox>

Javascript Function:
 function onlyOneDotAndNumbers(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;
        }

That’s it!!…..Happy Programming...

No comments:

Post a Comment