Page 1 of 1

Form Validator - Prevent submit if certain form fields empty

Posted: Tue Mar 15, 2005 6:43 am
by Cep
Hi,

I need to validate a form when the user hits submit.

Basically I want to say that if certain fields on the form have a value of " " then display a message box and prevent the form being submitted to the ASP file ELSE submit the form normally.

Now I came up with something but its not working because when I hit submit with the fields blank its being sent to the process.asp file with not message box appearing.

What is wrong with what I am doing?

In the header I put this,

Code: Select all

function checkIt(f)
{   
if (f.elementsї'Field1name'].value==&quote;&quote; && f.elementsї'Field2name'].value==&quote;&quote;)   
{      
alert('You have not specified the products you wish to order please go back to step 2');
     return false;   
}   
return true;
}

In the body I put this,

Code: Select all

<form method=&quote;post&quote; action=&quote;process.asp&quote; name=&quote;sForm&quote; onSubmit=&quote;return checkIt(this);&quote;>
...
Any ideas?

Posted: Tue Mar 15, 2005 7:03 am
by n00b Saibot
First thing that I saw was that you have put AND conditional instead of OR conditional in the if statement.
secondly, is your javascript error reporting on? does it give any errors of any sort?

Posted: Tue Mar 15, 2005 8:51 am
by Cep
Its meant to be and AND conditional. And no there aren't any errors being reported.

Posted: Tue Mar 15, 2005 10:27 am
by feyd

Code: Select all

&lt;?php

	if($_SERVERї'REQUEST_METHOD'] == 'POST')
	{
		var_export($_POST);
	}

?&gt;
&lt;html&gt;
	&lt;script language=&quote;Javascript&quote;&gt;
		function checkIt(f)
		{   
			if (f.elementsї'Field1name'].value==&quote;&quote; &amp;&amp; f.elementsї'Field2name'].value==&quote;&quote;)   
			{      
				alert('You have not specified the products you wish to order please go back to step 2');
				return false;   
			}   
			return true;
		}
	&lt;/script&gt;
	&lt;body&gt;
		&lt;form method=&quote;post&quote; name=&quote;sForm&quote; onSubmit=&quote;return checkIt(this);&quote;&gt;
			&lt;input name=&quote;Field1name&quote; type=&quote;text&quote; /&gt;
			&lt;input name=&quote;Field2name&quote; type=&quote;text&quote; /&gt;
			&lt;input name=&quote;sub&quote; type=&quote;submit&quote; /&gt;
		&lt;/form&gt;
	&lt;/body&gt;
&lt;/html&gt;

Posted: Tue Mar 15, 2005 10:31 am
by pickle
2 things:

I usually don't rely on the value being "". I usually check that the length is 0.

Also, I thought return was a function, therefore needing parentheses.

Posted: Wed Mar 16, 2005 9:56 am
by Cep
Cheers guys!