Click to See Complete Forum and Search --> : Very Basic Form Validation


mhaddon
09-12-2003, 03:30 PM
I am building a JSP application that cycles through various pages. I want to validate information from the user before the JSP processes. On the first JSP, I ask the user to select year ranges they are interested in. The basic validation I am trying to perform is ensuring the second year selected comes after or is the same as the first year selected (e.g. I don't want a range from 1994 to 1990, my query will fail).

Anyway the following is the script I have written to accomplish this:

<SCRIPT LANGUAGE=JavaScript>
function butCheckForm_onclick()
{
var myForm=document.form1;
if (myForm.year1.value > myForm.year2.value) {
alert("Second year selected must be greater or equal to first year selected");
myForm.year2.focus();
}
}
</SCRIPT>

Then I attach this function to the onclick method of my submit button. All works well, but when a user selects a first year that is larger than the second year, the alert box appears, but it has a Yes/No/Cancel format. I just want it to have an OK button and take the user back to the form to re-enter an appropriate year. What am I doing wrong?? Help!

Charles
09-12-2003, 03:38 PM
JavaScript will fail for 13% of users so be sure that you redundantly validate the form server side.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Content-Script-Type" content="text/javascript">
<title>Example</title>

<style type="text/css">
<!--
label {display:block; margin:1em 0em}
input {display:block}
-->
</style>

<form action="" onsubmit="if (this.firstYear.value > this.secondYear.value) {alert('The Second year needs to be greater than or equal to the First year'); this.secondYear.value = ''; this.secondYear.focus(); return false}">
<div>
<label>First Year<input type="text" name="firstYear"></label>
<label>Second Year<input type="text" name="secondYear"></label>
<button type="submit">Submit</button>
</div>
</form>