Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Resetting focus to a form field

Status
Not open for further replies.

brocsman

Programmer
Aug 28, 2003
11
GB
I want to validate a field in a form, using onblur. If the field is empty, or contains data in the wrong format, I display an error message alongside that field, using addmessage. So far so good.

Now I want to force the user to respond, so I want to restore focus to that field, and not let them carry on until it is correctly filled in.

I want to delete the error message at an appropriate point (not sure how to do this either - maybe a timeout?),so that if it fails a second time only the relevant error message is displayed.

I'm new to javascript. Hope that is not asking too much at once! Any links to working examples greatly appreciated.
 
This is the html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"<html xmlns=" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=iso-8859-1"/>
<title>Registration form example</title>
<script type="text/javascript" src="result.js"></script>


</head>
<body>


<h1>Submit Runner Time</h1>

<form name="demo" method="post" action="url">

<table>

<!-- runner id should not be empty and should be a number not a string -->
<tr><td>

Runner Id:
</td><td>
<input type="text" name="RunnerID" id="RunnerID" onblur= "runnerid_validate()" size="5" maxlength="5"/></td>
<td><p id="runiderr"></p></td></tr>

<!-- event id should not be empty and should be a number not a string -->
<tr><td>


Event Id:
</td><td>
<input type="text" name="EventID" id="EventID" onblur= "eventid_validate()" size="5" maxlength="5"/>
</td>
<td><p id="evtiderr"></p></td>
</tr>

<!-- date should not be empty and should be in yyyy-mm-dd format -->

<tr><td>
Date:
</td><td>
<input type="text" name="Date" id="Date" onblur=" date_validate()" size="10" maxlength="10"/>
</td>
<td><p id="dateerr"></p></td>
</tr>

<!-- finish time should not be empty and should be in hh:mm:ss format -->

<tr><td>
Finish Time:
</td><td>
<input type="text" name="FinishTime" id="FinishTime" onblur= "fintime_validate()" size="10" maxlength="10"/>
</td>
<td><p id="fintimerr"></p></td>
</tr>

<!-- position should be a number -->

<tr><td>
Position:
</td><td>
<input type="text" name="Position" id="Position" onblur= "position_validate()" size="5" maxlength="5"/>
</td>
<td><p id="poserr"></p></td>
</tr>

<!-- category should be a number in the reang 1-100 -->

<tr><td>
Category:
</td><td>
<input type="text" name="CategoryID" id="CategoryID" onblur= "category_validate()" size="3" maxlength="3"/>
</td>
<td><p id="caterr"></p></td>
</tr>

<!-- agegrade should be a number -->

<tr><td>
Age Grade:
</td><td>
<input type="text" name="AgeGrade" id="AgeGrade" onblur= "agegrade_validate()" size="5" maxlength="5"/>
</td>
<td><p id="ageerr"></p></td>
</tr>

<!-- personal best can be yes or no -->

<tr><td>
Personal Best:
</td><td>
<input name="PB" type="radio" value="0" checked="checked"> No
<input name="PB" value="1" type="radio"> Yes
</td>
<td><p id="pberr"></p></td>
</tr>


</table>



<input type="submit" value="Submit form" />
<p id ="errorMessage">
</p>

</form>
<script
type="text/javascript"
language="javascript">
document.getElementById("RunnerID").focus();
</script>
</body>
</html>




This is the js. No CSS yet.


// Add error message to invalid data entry
function addMessage(id, text)
{
var textNode = document.createTextNode(text);
var element = document.getElementById(id);
element.appendChild(textNode);
}



// Runner ID Validate
function runnerid_validate()
{
var RunnerID = document.getElementById('RunnerID').value;
var test_expression = /[0-9]+/

if (RunnerID.length >0){
if (test_expression.test(RunnerID)) {
return true;
}
else {
addMessage("runiderr","Must be a number in the range 1-99999");
document.getElementById('runiderr').style.background="yellow";



return false;





}
}
else {
addMessage("runiderr","Please enter your Runner ID");
document.getElementById('runiderr').style.background="yellow";
return false;
}

}

// Event ID Validate
function eventid_validate()
{
var EventID = document.getElementById('EventID').value;
var test_expression = /[0-9]+/

if (EventID.length >0){
if (test_expression.test(EventID)) {
return true;
}
else {
addMessage("evtiderr","Must be a number in the range 1-99999");
document.getElementById('evtiderr').style.background="yellow";
return false;
}
}
else {
addMessage("evtiderr","Please enter the Event ID");
document.getElementById('evtiderr').style.background="yellow";
return false;
}

}


// DATE Validate
function date_validate()
{
var Date = document.getElementById('Date').value;
var test_expression = /^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$/


if (Date.length >0){
if (test_expression.test(Date)) {
return true;
}
else {
addMessage("dateerr","Date must be in yyyy-mm-dd format");
document.getElementById('dateerr').style.background="yellow";
return false;
}
}
else {
addMessage("dateerr","Please enter a date in yyyy-mm-dd format");
document.getElementById('dateerr').style.background="yellow";
return false;
}

}


// Finish Time Validate
function fintime_validate()
{
var FinishTime = document.getElementById('FinishTime').value;
var test_expression = /^(?:(?:(\d+):)?(\d+):)?(\d+)/

if (FinishTime.length >0){
if (test_expression.test(FinishTime)) {
return true;
}
else {
addMessage("fintimerr","must be in hh:mm:ss format");
document.getElementById('fintimerr').style.background="yellow";
return false;
}
}
else {
addMessage("fintimerr","Please enter a Finish Time in hh:mm:ss format");
document.getElementById('fintimerr').style.background="yellow";
return false;
}

}


// Position Validate
function position_validate()
{
var Position = document.getElementById('Position').value;
var test_expression = /[0-9]+/

if (Position.length >0){
if (test_expression.test(Position)) {
return true;
}
else {
addMessage("poserr","Must be a number in the range 1-99999");
document.getElementById('poserr').style.background="yellow";
return false;
}
}
else {
addMessage("poserr","Please enter your Position");
document.getElementById('poserr').style.background="yellow";
return false;
}

}

// Category Validate
function category_validate()
{
var CategoryID = document.getElementById('CategoryID').value;
var test_expression = /[0-9]+/

if (CategoryID.length >0){
if (test_expression.test(CategoryID)) {
return true;
}
else {
addMessage("caterr","Must be a number in the range 1-99");
document.getElementById('caterr').style.background="yellow";
return false;
}
}
else {
addMessage("caterr","Please enter your Category ID");
document.getElementById('caterr').style.background="yellow";
return false;
}

}

// Age Grade Validate
function agegrade_validate()
{
var AgeGrade = document.getElementById('AgeGrade').value;
var test_expression = /^\s*-?\d+(\.\d{1,2})?\s*/

if (AgeGrade.length >0){
if (test_expression.test(AgeGrade)) {
return true;
}
else {
addMessage("ageerr","Must be a number with two decimal places");
document.getElementById('ageerr').style.background="yellow";
return false;
}
}
else {
addMessage("ageerr","Please insert Age Grade");
document.getElementById('ageerr').style.background="yellow";
return false;
}
}

Thanks
 
Hi

Sorry, but that looks horrible. This is a rewrite of your code to use a single function and show/hide messages without littering :
JavaScript:
[b]var[/b] rule[teal]=[/teal][teal]{[/teal]
  [green][i]'RunnerID'[/i][/green][teal]:[[/teal][green][i]'Please enter your Runner ID'[/i][/green][teal],[/teal][fuchsia]/[0-9]+/[/fuchsia][teal],[/teal][green][i]'Must be a number in the range 1-99999'[/i][/green][teal]],[/teal]
  [green][i]'EventID'[/i][/green][teal]:[[/teal][green][i]'Please enter the Event ID'[/i][/green][teal],[/teal][fuchsia]/[0-9]+/[/fuchsia][teal],[/teal][green][i]'Must be a number in the range 1-99999'[/i][/green][teal]],[/teal]
  [green][i]'Date'[/i][/green][teal]:[[/teal][green][i]'Please enter a date in yyyy-mm-dd format'[/i][/green][teal],[/teal][fuchsia]/^(19|20)\d\d[- /[/fuchsia][teal].]([/teal][purple]0[/purple][teal][[/teal][purple]1[/purple][teal]-[/teal][purple]9[/purple][teal]]|[/teal][purple]1[/purple][teal][[/teal][purple]012[/purple][teal]])[-[/teal] [fuchsia]/.](0[1-9]|[12][0-9]|3[01])$/[/fuchsia][teal],[/teal][green][i]'Date must be in yyyy-mm-dd format'[/i][/green][teal]],[/teal]
  [green][i]'FinishTime'[/i][/green][teal]:[[/teal][green][i]'Please enter a Finish Time in hh:mm:ss format'[/i][/green][teal],[/teal][fuchsia]/^(?:(?:(\d+):)?(\d+):)?(\d+)/[/fuchsia][teal],[/teal][green][i]'must be in hh:mm:ss format'[/i][/green][teal]],[/teal]
  [green][i]'Position'[/i][/green][teal]:[[/teal][green][i]'Please enter your Position'[/i][/green][teal],[/teal][fuchsia]/[0-9]+/[/fuchsia][teal],[/teal][green][i]'Must be a number in the range 1-99999'[/i][/green][teal]],[/teal]
  [green][i]'CategoryID'[/i][/green][teal]:[[/teal][green][i]'Please enter your Category ID'[/i][/green][teal],[/teal][fuchsia]/[0-9]+/[/fuchsia][teal],[/teal][green][i]'Must be a number in the range 1-99'[/i][/green][teal]],[/teal]
  [green][i]'AgeGrade'[/i][/green][teal]:[[/teal][green][i]'Please insert Age Grade'[/i][/green][teal],[/teal][fuchsia]/^\s*-?\d+(\.\d{1,2})?\s*/[/fuchsia][teal],[/teal][green][i]'Must be a number with two decimal places'[/i][/green][teal]],[/teal]
[teal]}[/teal]

[b]function[/b] [COLOR=darkgoldenrod]validate[/color][teal]([/teal]what[teal])[/teal]
[teal]{[/teal]
  [b]var[/b] message[teal]=[/teal][green][i]''[/i][/green]

  [b]if[/b] [teal]([/teal]what[teal].[/teal]value[teal]==[/teal][green][i]''[/i][/green][teal])[/teal] message[teal]=[/teal]rule[teal][[/teal]what[teal].[/teal]name[teal]][[/teal][purple]0[/purple][teal]][/teal]
  [b]else[/b] [b]if[/b] [teal](![/teal]rule[teal][[/teal]what[teal].[/teal]name[teal]][[/teal][purple]1[/purple][teal]].[/teal][COLOR=darkgoldenrod]test[/color][teal]([/teal]what[teal].[/teal]value[teal]))[/teal] message[teal]=[/teal]rule[teal][[/teal]what[teal].[/teal]name[teal]][[/teal][purple]2[/purple][teal]][/teal]

  what[teal].[/teal]parentNode[teal].[/teal]parentNode[teal].[/teal]cells[teal][[/teal][purple]2[/purple][teal]].[/teal]firstChild[teal].[/teal]innerHTML[teal]=[/teal]message

  [b]return[/b] message[teal]==[/teal][green][i]''[/i][/green]
[teal]}[/teal]
The function call should be like this, in all [tt]input[/tt]s :
Code:
[b]<input[/b] [maroon]type[/maroon][teal]=[/teal][green][i]"text"[/i][/green] [maroon]name[/maroon][teal]=[/teal][green][i]"RunnerID"[/i][/green] [maroon]id[/maroon][teal]=[/teal][green][i]"RunnerID"[/i][/green] [maroon]onblur[/maroon][teal]=[/teal][green][i]"validate(this)"[/i][/green] [maroon]size[/maroon][teal]=[/teal][green][i]"5"[/i][/green] [maroon]maxlength[/maroon][teal]=[/teal][green][i]"5"[/i][/green][b]/>[/b]
[ul]
[li]Some regular expressions are wrong. Especially the one for numbers. I suppose 0 for Runner ID and 99999 for Age Grade is not really valid.[/li]
[li]Forcing the focus can not be easily and nicely done. I suggest to give up on that. Just let the visitor fill the [tt]input[/tt]s in whatever order they want. As long as an error exists, the messages are displayed anyway.[/li]
[li]Think to those who will fill the Runner ID then click submit. You should do an extra validation [tt]onsubmit[/tt].[/li]
[li]Currently I just put the error message in the [tt]p[/tt] in the next [tt]td[/tt]. This works, but may get broken in the future. A consistent naming would help to automate the picking of right [tt]p[/tt] based on the [tt]input[/tt] [tt]name[/tt]s or [tt]id[/tt]s.[/li]
[li]Use CSS to decorate the error message [tt]p[/tt] elements.[/li]
[/ul]


Feherke.
 
I tend to agree with Feherke in reducing your validation functions to a single one if possible.

Secondly, for numbers I would not use a regular expression. But that's just my preference.

As far as the focus goes it can be done reliably across most browsers with a settimeout. As otherwise the focus happens before the blurr event is complete and is overridden.

JavaScript:
function validate_input(inputObj, rule, errorID, errormsg){
				
					 	if(isNaN(inputObj.value) || parseInt(inputObj.value) >= 999)
						{
							
[green]//if value is not a number or if it is a number but grater than the allowed amount: set the error message[/green]
							document.getElementById(errorID).innerHTML=errormsg;
[green]//set the removal of the error for later[/green]
							removeErr="document.getElementById('" + errorID + "').innerHTML=''";
[green]//prepare the focus event[/green]
							reFocus = "document.getElementById('" + inputObj.id + "').focus();";
[green]//set the focus to happen 50 milliseconds in the future, so the onblur event has concluded, and then reset focus. [/green]
							setTimeout(reFocus,50);
[green]//set the removal of the error after 5 seconds[/green]							setTimeout(removeErr,5000);
							return false;
						}
					 					
					}
					return true;
					
				}

And of course the call should be:
HTML:
<input type="text" name="mybox" value="" id="mybox" onblur="return validate_input([blue]this[/blue],'err','XXXX must be a number less than 999');"><span id="err" style="color:red;"></span>

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
Hi

Feherke said:
Forcing the focus can not be easily and nicely done.
I wrote that thinking to the same [tt]setTimeout()[/tt] trick, which is easy, but not nice. If there will be two consecutive non-validating [tt]input[/tt]s, leaving the first towards the second will enter a crazy focus ping-pong.

With the emptiness check skipped as in Phil's code, such ping-pong is hardly achieved during the manual filling process, but some autofill by the browser or an extension can still lead to that situation. Adding the emptiness check too, will directly drop the visitor in the ping-pong on the first error ( unless failing on the last [tt]input[/tt] ).

The easiest correction to this is the use of a global variable ( also not considered nice by many professionals ) :
Code:
[highlight][b]var[/b] error[teal]=[/teal][b]false[/b][/highlight]

[b]function[/b] [COLOR=darkgoldenrod]validate[/color][teal]([/teal]what[teal])[/teal]
[teal]{[/teal]
  [highlight][b]if[/b] [teal]([/teal]error[teal])[/teal] [b]return[/b][/highlight]

  [b]var[/b] message[teal]=[/teal][green][i]''[/i][/green]

  [b]if[/b] [teal]([/teal]what[teal].[/teal]value[teal]==[/teal][green][i]''[/i][/green][teal])[/teal] message[teal]=[/teal]rule[teal][[/teal]what[teal].[/teal]name[teal]][[/teal][purple]0[/purple][teal]][/teal]
  [b]else[/b] [b]if[/b] [teal](![/teal]rule[teal][[/teal]what[teal].[/teal]name[teal]][[/teal][purple]1[/purple][teal]].[/teal][COLOR=darkgoldenrod]test[/color][teal]([/teal]what[teal].[/teal]value[teal]))[/teal] message[teal]=[/teal]rule[teal][[/teal]what[teal].[/teal]name[teal]][[/teal][purple]2[/purple][teal]][/teal]

  what[teal].[/teal]parentNode[teal].[/teal]parentNode[teal].[/teal]cells[teal][[/teal][purple]2[/purple][teal]].[/teal]firstChild[teal].[/teal]innerHTML[teal]=[/teal]message

  [highlight][b]if[/b] [teal]([/teal]message[teal])[/teal] [teal]{[/teal][/highlight]
    [highlight]error[teal]=[/teal][b]true[/b][/highlight]
    [highlight][COLOR=darkgoldenrod]setTimeout[/color][teal]([/teal][b]function[/b][teal]()[/teal] [teal]{[/teal] what[teal].[/teal][COLOR=darkgoldenrod]focus[/color][teal]();[/teal] error[teal]=[/teal][b]false[/b] [teal]}[/teal][teal],[/teal][purple]50[/purple][teal])[/teal][/highlight]
  [highlight][teal]}[/teal][/highlight]

  [b]return[/b] message[teal]==[/teal][green][i]''[/i][/green]
[teal]}[/teal]
Feherke said:
Think to those who will fill the Runner ID then click submit. You should do an extra validation [tt]onsubmit[/tt].
Passing the error message element's [tt]id[/tt] and the error message as parameters on function call is certainly easier to understand than my structured data object. But if an [tt]onsubmit[/tt] validation as I suggested will also be implemented, then those function parameters will have to be reproduced in another place.

By the way, Phil. You have an extra formal parameter in your [tt]function[/tt] declaration.

Feherke.
 
All true. The input ping-pong is a major concern with the timeout method.

The refocusing of an element is not something that should be needed in most cases.

I also agree a comprehensive check before submitting would be better, in fact instead of checking every input when its filled in, just perform a general check before submission.

Of course Javascript alone should never be trusted either so a server-side check of the data entered is also strongly advised.

As for the extra parameter yes I left it there as I was trying out a general rule scenario with a switch statement, and forgot to remove it.

At the end focusing is not something that should be forced. A more comprehensive check before submission is always better, and a server-side check of the received data is also highly advised to make sure no errors got past JS.

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
Thanks for all the help. I did say I was new to javascript, so it might take me a while to digest it all, but I'll probably be back with more questions soon!
 
I know my code is not elegant. All I want is for it to work. I have taken your advice, and now pulled all the error checking functions together, and called them from a function related to an onSubmit event. This issues an alert that there are errors, the error messages are displayed as I want them, but then when I dismiss the alert the form gets submitted anyway.

How do I get it to stop and wait for the errors to be corrected?
 
Hi

Supposing your new function still returns boolean signaling whether the validation passed, just [tt]return[/tt] it :
Code:
[b]<form[/b] [maroon]name[/maroon][teal]=[/teal][green][i]"demo"[/i][/green] [maroon]method[/maroon][teal]=[/teal][green][i]"post"[/i][/green] [maroon]action[/maroon][teal]=[/teal][green][i]"url"[/i][/green] [maroon]onsubmit[/maroon][teal]=[/teal][green][i]"[highlight]return[/highlight] validate()"[/i][/green][b]>[/b]

Feherke.
 
Thanks. Still being stupid this end.

My function needs to be called to make it carry out the validation. If I use "return validateForm" in the onsubmit event I get true, as the function hasn't been called, so the form submits without validating.

Where do I put the function call so that the form is validated prior to the onsubmit event?

 
Hi

Post your current code. We have no idea what and how you changed in meantime.

This time please post your code between [tt][ignore]
Code:
[/ignore][/tt] and [tt][ignore]
[/ignore][/tt] TGML tags.

Feherke.
 
Sorry - never used this before. Is this what you mean?

Code:
var errpresent = false;

function validateForm(){

runnerid_validate()
runnerid_validate()
eventid_validate()
date_validate()
fintime_validate()
position_validate()
category_validate()
agegrade_validate()

if (errpresent == true){
    alert("Please correct the highlighted errors");
    return false;

}
}



// Add error message to invalid data entry

function addMessage(id, text) 

	{

		var textNode = document.createTextNode(text);

		var element = document.getElementById(id);

		element.appendChild(textNode);

	}







// Runner ID Validate

function runnerid_validate()

{

	var RunnerID = document.getElementById('RunnerID').value;															

	var test_expression = /[0-9]+/

	

	if (RunnerID.length >0){

		if (test_expression.test(RunnerID)) 	{

			return true;

		}

		else 	{

                         addMessage("runiderr","Must be a number in the range 1-99999");

                         document.getElementById('runiderr').style.background="yellow";

                         errpresent =true;

                         return false;

		}

	}

	else {

                        addMessage("runiderr","Please enter your Runner ID");

                        document.getElementById('runiderr').style.background="yellow";
                        errpresent =true;

		        return false;

	}

			

}



// Event ID Validate

function eventid_validate()

{

	var EventID = document.getElementById('EventID').value;															

	var test_expression = /[0-9]+/

	

	if (EventID.length >0){

		if (test_expression.test(EventID)) 	{

			return true;

		}

		else 	{

                         addMessage("evtiderr","Must be a number in the range 1-99999");

                         document.getElementById('evtiderr').style.background="yellow";
                         errpresent =true;

			 return false;

		}

	}

	else {

                        addMessage("evtiderr","Please enter the Event ID");

                        document.getElementById('evtiderr').style.background="yellow";
                        errpresent =true;

		        return false;

	}

			

}





// DATE Validate

function date_validate()

{

	var Date = document.getElementById('Date').value;															

	var test_expression = /^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$/





	if (Date.length >0){

		if (test_expression.test(Date)) 	{

			return true;

		}

		else 	{

                         addMessage("dateerr","Date must be in yyyy-mm-dd format");

                         document.getElementById('dateerr').style.background="yellow";
                         errpresent =true;

			 return false;

		}

	}

	else {

                         addMessage("dateerr","Please enter a date in yyyy-mm-dd format");

                         document.getElementById('dateerr').style.background="yellow";
                         errpresent =true;

 			 return false;

	}

																									

}





// Finish Time Validate

function fintime_validate()

{

	var FinishTime = document.getElementById('FinishTime').value;															

	var test_expression = /^(?:(?:(\d+):)?(\d+):)?(\d+)/

	

	if (FinishTime.length >0){

		if (test_expression.test(FinishTime)) 	{

			return true;

		}

		else 	{

                         addMessage("fintimerr","must be in hh:mm:ss format");

                         document.getElementById('fintimerr').style.background="yellow";
                         errpresent =true;

			 return false;

		}

	}

	else {

                        addMessage("fintimerr","Please enter a Finish Time in hh:mm:ss format");

                        document.getElementById('fintimerr').style.background="yellow";
                        errpresent =true;

		        return false;

	}

			

}





// Position Validate

function position_validate()

{

	var Position = document.getElementById('Position').value;															

	var test_expression = /[0-9]+/

	

	if (Position.length >0){

		if (test_expression.test(Position)) 	{

			return true;

		}

		else 	{

                         addMessage("poserr","Must be a number in the range 1-99999");

                         document.getElementById('poserr').style.background="yellow";
                         errpresent =true;

			 return false;

		}

	}

	else {

                        addMessage("poserr","Please enter your Position");

                        document.getElementById('poserr').style.background="yellow";
                        errpresent =true;

		        return false;

	}

			

}



// Category Validate

function category_validate()

{

	var CategoryID = document.getElementById('CategoryID').value;															

	var test_expression = /[0-9]+/

	

	if (CategoryID.length >0){

		if (test_expression.test(CategoryID)) 	{

			return true;

		}

		else 	{

                         addMessage("caterr","Must be a number in the range 1-99");

                         document.getElementById('caterr').style.background="yellow";
                         errpresent =true;

			 return false;

		}

	}

	else {

                        addMessage("caterr","Please enter your Category ID");

                        document.getElementById('caterr').style.background="yellow";
                        errpresent =true;

		        return false;

	}

			

}



// Age Grade Validate

function agegrade_validate()

{

	var AgeGrade = document.getElementById('AgeGrade').value;															

	var test_expression = /^\s*-?\d+(\.\d{1,2})?\s*/

	

	if (AgeGrade.length >0){

		if (test_expression.test(AgeGrade)) 	{

			return true;

		}

		else 	{

                         addMessage("ageerr","Must be a number with two decimal places");

                         document.getElementById('ageerr').style.background="yellow";
                         errpresent =true;

			 return false;

		}

	}

	else {

                        addMessage("ageerr","Please insert Age Grade");

                        document.getElementById('ageerr').style.background="yellow";
                        errpresent =true;

		        return false;

	}

}
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

  "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]

<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml"[/URL] xml:lang="en" lang="en">

<head>

<meta http-equiv="Content-type" content="text/html; charset=iso-8859-1"/>

<title>Registration form example</title>

<script type="text/javascript" src="les20.js"></script>





</head>

<body>





<h1>Submit Runner Time</h1>



<form name="demo" method="post" ONSUBMIT= return "validateForm()" action="[URL unfurl="true"]http://lh6943.tt284.open.ac.uk/files/resultstestv1.php">[/URL]



<table>



<!-- runner id should not be empty and should be a number not a string  -->

<tr><td>



Runner Id:

</td><td> 

<input type="text" name="RunnerID" id="RunnerID" size="5" maxlength="5"/></td>						

<td><p id="runiderr"></p></td></tr>



<!-- event id should not be empty and should be a number not a string  -->

<tr><td>





Event Id:

</td><td> 

<input type="text" name="EventID" id="EventID" size="5" maxlength="5"/>			

</td>

<td><p id="evtiderr"></p></td>

</tr>



<!-- date should not be empty and should be in yyyy-mm-dd format  -->



<tr><td>

Date:

</td><td> 

<input type="text" name="Date" id="Date" size="10" maxlength="10"/>

</td>

<td><p id="dateerr"></p></td>

</tr>



<!-- finish time should not be empty and should be in hh:mm:ss format  -->



<tr><td>

Finish Time:

</td><td> 

<input type="text" name="FinishTime" id="FinishTime" size="10" maxlength="10"/>

</td>

<td><p id="fintimerr"></p></td>

</tr>



<!-- position should be a number   -->



<tr><td>

Position:

</td><td> 

<input type="text" name="Position" id="Position" size="5" maxlength="5"/>

</td>

<td><p id="poserr"></p></td>

</tr>



<!-- category should be a number in the reang 1-100   -->



<tr><td>

Category:

</td><td> 

<input type="text" name="CategoryID" id="CategoryID" size="3" maxlength="3"/>

</td>

<td><p id="caterr"></p></td>

</tr>



<!-- agegrade should be a number   -->



<tr><td>

Age Grade:

</td><td> 

<input type="text" name="AgeGrade" id="AgeGrade" size="5" maxlength="5"/>

</td>

<td><p id="ageerr"></p></td>

</tr>



<!-- personal best can be yes or no  -->



<tr><td>

Personal Best:

</td><td> 

<input name="PB" type="radio" value="0" checked="checked"> No

<input name="PB" value="1" type="radio"> Yes

</td>

<td><p id="pberr"></p></td>

</tr>





</table>







<input type="submit"   value="Submit form" > 

<p id ="errorMessage"> 

</p>



</form>



</body>

</html>
 
Hi

Yes, it is much readable this way. However that double spacing is abit irritating.
[ul]
[li]Please write valid HTML. I mean no windblown attributes, with value and name separated by whitespaces.[/li]
[li]Make sure your validateForm() function always [tt]return[/tt]s a defined value. Currently it [tt]return[/tt]s either [tt]false[/tt] or [tt]undefined[/tt].[/li]
[li]Make sure your errpresent gets reset before each use. Currently once set to [tt]true[/tt], will never ever become [tt]false[/tt] again even if the errors are corrected later.[/li]
[/ul]


Feherke.
 
I told you I was new to this!

No idea where the double spacing has come from. It's not there in my text editor.

"Please write valid HTML. I mean no windblown attributes, with value and name separated by whitespaces."

Give me an example and I'll try to improve.

"Make sure your validateForm() function always returns a defined value. Currently it returns either false or undefined."

Point taken.

"Make sure your errpresent gets reset before each use. Currently once set to true, will never ever become false again even if the errors are corrected later."

I think it just needs resetting after the alert, which I've done.

I still need a hand about where and how to call the function before the onSubmit event.

Thanks again.
 
This double spacing seems to be caused by the input box on this form. I'm typing single spacing, and it appears double.

This is how my function looks now:

var errpresent = false;
function validateForm(){
runnerid_validate()
eventid_validate()
date_validate()
fintime_validate()
position_validate()
category_validate()
agegrade_validate()
if (errpresent == true){
alert("Please correct the highlighted errors");
errpresent = false;
return false;
}
else
return true;
}

HTH
 
Hi

brocsman said:
"Please write valid HTML. I mean no windblown attributes, with value and name separated by whitespaces."

Give me an example and I'll try to improve.
Code:
                           [gray]remove this --v[/gray]
<form name="demo" method="post" ONSUBMIT=[highlight] [/highlight][highlight pink]return [/highlight]"validateForm()" action="[URL unfurl="true"]http://lh6943.tt284.open.ac.uk/files/resultstestv1.php">[/URL]
                              [gray]move this --^^^^^^^ ^-- here[/gray]

[gray]<!-- to get this : -->[/gray]
[b]<form[/b] [maroon]name[/maroon][teal]=[/teal][green][i]"demo"[/i][/green] [maroon]method[/maroon][teal]=[/teal][green][i]"post"[/i][/green] [maroon]ONSUBMIT[/maroon][teal]=[/teal][green][i]"return validateForm()"[/i][/green] [maroon]action[/maroon][teal]=[/teal][green][i]"[URL unfurl="true"]http://lh6943.tt284.open.ac.uk/files/resultstestv1.php"[/URL][/i][/green][b]>[/b]

Feherke.
 
Agreed.

Your errpresent variable being global will retain the value it's given. Since your functions never set it back to false, your function will always return false regardless.

The return portion of the on submit event should also be inside the quotes. It's a complete command. Not sure why you chose to set it outside.

Code:
onsubmit="[red]return[/red] formValidate();"

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top