Numeric Validation in Java Script

By Sai Kumar May 21, 2012
Java Script code For Numeric Validation.

In your html page add the control you want to validate but for this sample I used textbox to demonstrate this code, in my textbox control I used onkeyup event to validate whether recently entered charecter is numeric or not. so you can call this JavaScript code as your requirement in your project

Test.html

<input type="text" id="txt" name="txt" onkeyup="txtValidate(this.id)"/>
 

JavaScript Code
 

function txtValidate(txtid) {

        var ok = 0;

        var a = document.getElementById(txtid).value;

 

        for (var i = 0; i <= a.length - 1; i++) {

            var j = a.charCodeAt(i);

            for (var k = 48; k <= 57; k++) {

                ok = 0;

                if (k == j) {

                    ok = 1;

                    break;

                }

            }

 

        }

        if (ok == 0) {

            alert("Only Numeric Values Allowed");

            document.getElementById(txtid).value = "";

            for (var i = 0; i < a.length - 1; i++) {

                var j = a.charCodeAt(i);

                for (var k = 48; k <= 57; k++) {

                    ok = 0;

                    if (k == j) {

                        document.getElementById(txtid).value += a.charAt(i);

                    }

                }

 

            }

        }

    }



I hope this code helps you.

Thank you.

 

Sai Kumar

I work as Sr.Software Engineer at Flex Informatics Pvt. Ltd., and love to sare my knowledge to all through blogging and MSDN Forums. I maintain my own blog http://saimaterial.wordpress.com through which i share some arti... Read more

COMMENT USING

PREMIUM SPONSORS

Hire Mobile & Web Developer on demand. 100% satisfaction. Try for 1 week or Money Back. Local and remote developers available all over USA.

Latest Blogs