Welcome to WebmasterWorld Guest from

Forum Moderators: open

Message Too Old, No Replies

Javascript Validation

How to validate all form elements?



7:04 am on Jul 22, 2002 (gmt 0)

10+ Year Member

Hi all.

I have a form with some elements. Each element can hold data of any one of the different types as text,date or integer values. I need to validate all the elements in the client side itself i.e I have to check if the element is meant for specific type of data for eg.integer. If it contains data other than integer, then alert a message to the user.

The definition for the type of the data which the element is holding is defined in an xml file.

I am using JSP and Servlet.

Can anyone tell me how I can do this? Or can anyone give me a piece of js code that is generalised for validating all elements in the form?

Thanks in advance.


9:08 am on Jul 22, 2002 (gmt 0)

10+ Year Member

JavaScript is a very loosely-typed language, which means there is no way to cast variables -- not officially, at least. This is a problem, because form input values are read in as strings. However, you can force JavaScript to make the necessary conversion from string to number by simply subtracting zero:

var myNumber=myString-0

(You can also multiply or divide by 1: but you can't add 0, because the + operator will convert the zero to the string "0" and then concatenate, effectively multiplying an integer by 10.)

To convert a string to an integer, use parseInt(). This accepts a string, and returns as a number the left-most digits as far as the first character which is not a digit -- so parseInt('100 dollars') becomes the number 100, and parseInt('13.6') becomes 13. If the string does not start with a digit, the function will return NaN.

Putting these things together, to test for an integer, use the following:


You need to check each field that requires an integer in this way. Text input field values are available to JavaScript as:


where formName is the value of <form name="..."> and elementName is the value of <input name="...">

When I validate forms, I usually define an empty string called, perhaps, errmsg. Every time the script encounters an error, I add a description of the error to errmsg -- for example:

if(parseInt(document.myForm.numUnits.value)!=document.myForm.numUnits.value-0) errmsg+='\nYou can only order a whole number of units';

At the end of the validation script, I test errmsg. If it contains the empty string, the form is correct (no errors) and can be submitted. Otherwise, it should display an error message and cancel the form submission process:

if(errmsg=='') return true;
alert('The form could not be submitted because it contained the following error(s):\n'+errmsg);
return false;

This should be stored in a function called, say, check(). It is then invoked by the onsubmit() handler like this:

<form name="myForm" onsubmit="return check();">

As a short cut you can use the this keyword: if you write the <form> tag like this:

<form name="myForm" onsubmit="return check(this);">

"this" refers to the form. The function declaration can look like this:

function check(f){ ... }

...and instead of document.myForm.numUnits.value you can write f.numUnits.value.

You can't rely on client-side validation though, since you can't rely on JavaScript being enabled in the browser. It must be in addition to your server-side script. Look on it as an extra service for those fortunate enough to have JavaScript, not as a foolproof way to cut down on your server-side programming.

If this post doesn't mean much to you, I'd advise you not to try it until you have got to grips with JavaScript. It's a tricky language, and if you get it slightly wrong it is worse than useless.


9:13 am on Jul 22, 2002 (gmt 0)

10+ Year Member

Unfortunatly, you didn't write what field type are you talking about. It seems like it should be type="text", but who knows...

If you want to validate the entire form you should be able to handle all kings of form elements. Here's a basic script that you need (it checks only text and select fields, but you can add other types as well):

function checkAll(formname) {

for (n=0; n<formname.elements.length; n++)
if (formname.elements[n].type=="text")

else if (formname.elements[n].type=="select-one")

else if (formname.elements[n].type=="select-multiple")

This function should return "true" or "false" value depending on validation result. And you should call it like this:

<form name="" action="" onSubmit="return checkAll()">

Then you have to write validation functions for every element type. For example, for text fields you'll need to use parseInt() and parseFloat() functions to check if a value entered is an integer or floating-point number. Here's a basic example:

function validateText(numb){

if (parseInt(numb)=="Nan")
alert("this is not an integer value")
return false

return true

good luck


7:41 pm on Jul 22, 2002 (gmt 0)

10+ Year Member

if (parseInt(numb)=="Nan")
This won't work for three reasons:

1. The "Not-a-number" value is represented as NaN (upper-case N, lower-case a, upper-case N)

2. NaN should not be in quotes. "NaN" is interpreted not as the not-a-number value, but as a string containing three characters, N, a and N.

3. Any equality test involving NaN will always return false, even if you compare it to itself. The only way to test for NaN is to use the JavaScript function isNaN() which returns true if the value is the NaN value, as might be returned by a division by zero or a function such as parseInt().

Your test should therefore be written:


This may not have the desired effect, however. If the value of numb is "ten" or "$20", then the test will work as expected because parseInt() will return NaN. However, consider the case where numb="15.8". The test will be equivalent to:


parseInt works like this: it looks at the first character and finds a digit, so, whatever else it does, it doesn't return NaN. The second character is also a digit. The third character, however, is not, so parseInt() takes the portion of the string to the left of the decimal point and converts it to a number: 15. This is the value it returns, so the test is now:


15 is not NaN, so the test resolves to false and the error message is not displayed even though the user did not type in an integer. The original value "15.8" is still stored in the variable numb. That's why I test the parsed value against the value typed in.

If, on the other hand, you don't mind accepting a decimal number and discarding the decimal portion, you'll need to assign the return value of parseInt() to numb and test that:


This will, however, always round down (e.g. 15.8 to 15). To round to the nearest integer (15.8 to 16), use Math.round():



6:38 am on Jul 23, 2002 (gmt 0)

10+ Year Member

Thank you rewboss for correcting me. Of course what I said is an error (the rule is not to hurry when you post to the forum). I just wanted to show the general idea of form validation, without getting deeply into details.
The correct comparison statement is this:
if (isNaN(parseInt(numb)))

or this:
if ((parseInt(numb).NaN)

this should also work well.


12:28 pm on Jul 23, 2002 (gmt 0)

10+ Year Member

Thanks boss and star for the help. It worked fine.

Featured Threads

Hot Threads This Week

Hot Threads This Month