adsense

Wednesday, November 14, 2012

javascript for validating numeric text

Following javascript can be used to validate numerical values for a textbox. This validates  numbers without decimal points. If you want to validate decimals and thousand separators as well , you'll have to change the regex and call another javascript onblur event to validate the thousand separator and decimal point. I will post the javascript for this soon.

<script type="text/javascript">

 function validateOnlyNumber(evt) {
        var theEvent = evt || window.event;
        var key = theEvent.keyCode || theEvent.which;
        key = String.fromCharCode(key);
        var regex = /^\s*\d+\s*$/;
        if (!regex.test(key)) {
            theEvent.returnValue = false;
            if (theEvent.preventDefault) theEvent.preventDefault();
        }
    }

        function checkNumbers() {
            var ValidChars = /^\s*\d+\s*$/;
            var pasteData = window.clipboardData.getData("Text");


            if (ValidChars.test(pasteData))
                return true;
            else {
             
                return false;
            }
        }

        
 </script>


Call the functions as follows

<asp:TextBox ID="txtSearch" runat="server"   onpaste="return checkNumbers()"  onkeypress='validateOnlyNumber(event)'></asp:TextBox>

Cheers
Samitha

1 comment: