Contact Form Question

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
User avatar
php-forum Fan User
php-forum Fan User
Posts: 979
Joined: Thu Feb 17, 2011 6:52 am
Location: Racine, WI

Fri Apr 01, 2011 6:20 am

You could just do the verification before the form is sent with JavaScript like so:

Code: Select all

<script type="text/javascript">
function validate_required(field,alerttxt){
			with (field)
			  if (value==null||value=='')
				alert(alerttxt);return false;
				return true;
		function validate_form(thisform)
			with (thisform)
			  if (validate_required(name,'You must enter your name')==false)
			  {name.focus();return false;}
			  if (validate_required(Email,'You must enter your e-mail address')==false)
			  {Email.focus();return false;}
                          if (validate_required(Enquiry,'You must supply an Enquiry')==false)
			  {Enquiry.focus();return false;}
 <form action="php/contact.php" OnSubmit="return validate_form(this)" method="post" name="ContactForm">
                                       <br /><input name="Name" type="text" />
                                    <br /><label>Company:</label>
                                       <br /><input name="Company" type="text" />
                                    <br /><label>Email*:</label>
                                       <br /><input name="Email" type="text" />
                                    <br /><label>Phone:</label>
                                       <br /><input name="Phone" type="text" />
                                    <br /><label>Enquiry*:</label>
                                       <br /><textarea name="Enquiry"></textarea>
                                    <br /><input name="submit" type="submit" value="Submit" class="btn" />
                                    *Required Field
Pardon the formatting but essentially what I did was took your code and added 2 JavaScript Functions. The first "validate_required" takes a form element and checks if data has been entered into it, if not it pops up a box with an error message and focuses on the offending form element.

The second "validate_form" takes a form as an argument and checks each element that is declared as required using the validate_required function.

There is a pure html solution for just checking if a form is blank but it has compatibility issues. This solution also allows you to validate elements with other functions. I use this basic function to validate zipcodes, phone numbers, and e-mail addresses using regular expressions just by having validate_form call other functions I write.

Post Reply