1. Home
  2. Computing & Technology
  3. JavaScript

Calculator Tutorial

7. Validating Input

clr gif

The seventh step in creating out calculator is to add the necessary validations into the external Javascript to validate that the input fields have been entered correctly.

My Easter Calculator only has one input field so I only need to validate one field but if you have multiple fields then you will need to validate each separately and perhaps also include some cross field validations.

The year field on my form needs to be validated to ensure that something is entered. That field must be numeric and since the formula I am using presumes the Gregorian calendar, let's restrict it to years between 1582 and 2200. To do this I have added the following code into the function:

var year = calc.year.value;
if (year == '') {alert('Year must be entered.');
continued from previous linecalc.year.focus();return false;}
if (year != parseInt(year) || year < 1582 || year > 2200)
continued from previous line{alert('Year invalid (must be numeric between
continued from previous line 1582 and 2200).');calc.year.focus();return false;}

This code performs the required validations quickly and pops up an alert if an invalid value is entered. If you are not sure how to set up the validations that you require for the input fields in your calculator then take a look at the Validating Forms tutorials.

With the necessary validation added our calculator now functions correctly.

Year:
Day:
Month:

The only thing left to do now is to pretty it with style sheets to make it look like a calculator.

1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
Explore JavaScript
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.