homepage Welcome to WebmasterWorld Guest from 54.226.43.155
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
Javascript Validation
How to validate all form elements?
Jaya




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

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.

 

rewboss




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

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:

if(parseInt(myValue)!=myValue-0)

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

document.formName.elementName.value

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.

starway




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

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")
validateText(formname.elements[n].value)

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

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

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
}

else
return true
}

good luck

rewboss




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

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:

if(isNaN(parseInt(numb)))

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:

if(isNaN(parseInt("15.8")))

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:

if(isNaN(15))

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:

numb=parseInt(numb);
if(isNaN(numb)){...}

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():

numb=Math.round(numb-0);

starway




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

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.

Jaya




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

Thanks boss and star for the help. It worked fine.
:-)

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved