T-XU.COM      
Home |
  Home>Computer Programming>Javascript>
Validating Numerical Input with JavaScript
By David Morse        [Hits: 22570]



What? Make a mistake entering data? Who me? NO WAY! Right¡­

Every form of data input by a user should be validated in someform or fashion. If you get

clean data in, you won¡¯t get garbage out. This tutorial is goingto explain how to validate

numerical data entered into a form using JavaScript.

First, let us begin with the code to insert the JavaScript intoyour HTML document.

Place these lines between the and tags.

This line tells the web browser to expect some JavaScript codeand signal the beginning of

the script:



So now the format should look something like this:

My Title





Now on to validating the numerical input.

First we will create a function with one arument:

function validate(mydata){

These lines will test for a blank enty then prompt the user forinput:

if (mydata == ""){ alert("Please enter a number.") }

Next we will create a for loop which will look at each characterin the data until it

reaches the end:

for(var i=0;i < mydata.length;i++){

Now create a variable and assign the counter variable value toit:

var mydigit = mydata.charAt(i)

To screen out symbols, punctuation, and letters, place an ifstatement in the loop:

if(mydigit < "0" || mydigit > "9"){

The || in the if statement scans for both conditions.

The next line will alert the user to any mistakes he/she hasmade:

alert(mydigit + " is not a number.")

Here is the complete code including HTML:============================================= Numerical Validation

Guess anumber between 1 and 1000:

=============================================

You can test the above code by copying and pasting it into atext document then view it in

your browser.

And that's how easy it is to test user input for numericalinput.
  Top Articles
*Using External JavaScript File
*Simplified form to mail: Unlim
*Capturing Video And Audio Stre
*Building HTML codes automatica
*How to handle web surfers, who
*Instant plug-in scripts that h
*Anti right-click pop up : pop
*New Customizable JavaScript Me
*Ask Mr. D - JavaScript
*Inexpensive Area Rugs Give You
*Spice Up Your Web Site with Ja
*Evaluation of Keywords for an
  Related Articles
*How to test for the Javascript
*Instant plug-in scripts that h
*Javascript Password Protection
*Javascript Basics 01
*Building HTML codes automatica
*Javascript; Browser Detection
*Password protected document :
*Ask Mr. D - JavaScript
*On mouse over pop up: open pop
*Grow Your Subscribers Exponent
*Anti right-click pop up : pop
*Some Useful JavaScript Tricks


Prev: How to test for the Javascript DOM?   Next: Instant plug-in scripts that help you profit... "Special offer expiry date with



Home | Site Map | Bookmark this site | T-XU RSS
Copyright 2007 T-XU.com - All Rights Reserved Worldwide.