Solved

jquery validation script

Posted on 2010-11-20
7
792 Views
Last Modified: 2012-05-10
I am 95% completed with basic mail form. The validation script is powered by a mixture of php and jquery. All in all it works fine. I am however having some issues confirming that the email address was entered correctly (IE re type your email).

Suggestions or pointers very welcome.
Thanks,
N

<?php
//If the form is submitted
if(isset($_POST['submit'])) {

	//Check to make sure that the name field is not empty
	if(trim($_POST['contactname']) == '') {
		$hasError = true;
	} else {
		$name = trim($_POST['contactname']);
	}

	//Check to make sure that the subject field is not empty
	if(trim($_POST['subject']) == '') {
		$hasError = true;
	} else {
		$subject = trim($_POST['subject']);
	}

	//Check to make sure sure that a valid email address is submitted
	if(trim($_POST['email']) == '')  {
		$hasError = true;
	} else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
		$hasError = true;
	} else {
		$email = trim($_POST['email']);
	}
	
		//Check to make sure sure that the entered valu is the same as the entered email address
	if(trim($_POST['confirm_email']) == '')  {
		$hasError = true;
	} else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['confirm_email']))) {
		$hasError = true;
	} else if (trim($_POST['confirm_email']) !== $email)  {
		$hasError = true;
	} else {
		$confirm_email = trim($_POST['confirm_email']);
	}

	//Check to make sure comments were entered
	if(trim($_POST['message']) == '') {
		$hasError = true;
	} else {
		if(function_exists('stripslashes')) {
			$comments = stripslashes(trim($_POST['message']));
		} else {
			$comments = trim($_POST['message']);
		}
	}

	//If there is no error, send the email
	if(!isset($hasError)) {
		$emailTo = 'name@myemail.com'; //Put your own email address here
		$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
		$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

		mail($emailTo, $subject, $body, $headers);
		$emailSent = true;
	}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 
<head>
	<title></title>
	<meta http-equiv="content-type" content="text/html;charset=utf-8" />
	<meta http-equiv="Content-Style-Type" content="text/css" />
	<meta name="robots" content="noindex, nofollow" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script src="http://www.beaconhilldesign.co.nz/jquery/form-validation/jquery.validate.pack.js" type="text/javascript"></script>
 
<script type="text/javascript"> 
$(document).ready(function(){
	$("#contactform").validate();
});
</script>
	
<style type="text/css"> 
body {
	font-family:Arial, Tahoma, sans-serif;
}
#contact-wrapper { 
	width:430px; 
	border:1px solid #e2e2e2; 
	background:#f1f1f1; 
	padding:20px;
}
#contact-wrapper div { 
	clear:both; 
	margin:1em 0;
}
#contact-wrapper label { 
	display:block; 
	float:none; 
	font-size:16px; 
	width:auto; 
}
form#contactform input { 
	border-color:#B7B7B7 #E8E8E8 #E8E8E8 #B7B7B7; 
	border-style:solid; 
	border-width:1px; 
	padding:5px; 
	font-size:16px; 
	color:#333; 
}
form#contactform textarea { 
	font-family:Arial, Tahoma, Helvetica, sans-serif; 
	font-size:100%; 
	padding:0.6em 0.5em 0.7em; 
	border-color:#B7B7B7 #E8E8E8 #E8E8E8 #B7B7B7; 
	border-style:solid; 
	border-width:1px;
}
</style>
</head>
 
<body>
	<div id="contact-wrapper">
	
		<?php if ($emailSent == true) {
		echo"	<p><strong>Email Successfully Sent!</strong></p>
		<p>Thank you <strong>".$name."</strong> for using my contact form! Your email was successfully sent and I will be in touch with you soon.</p>";
		}else{
			echo"<p>Contact Us</p>";
			}
		?>
		
	<form method="post" action="index.php" id="contactform">					
		<div>
		    <label for="name"><strong>Name:</strong></label> 
			<input type="text" size="50" name="contactname" id="contactname" value="" class="required" />
		</div>
		
		<div>
			<label for="email"><strong>Email:</strong></label> 
			<input type="text" size="50" name="email" id="email" value="" class="required email" />
		</div>
        
        	<div>
			<label for="confirm_email"><strong>Confirm Email:</strong></label> 
			<input type="text" size="50" name="confirm_email" id="confirm_email" value="" class="confirm email" />
		</div>
		
		<div>
			<label for="subject"><strong>Subject:</strong></label> 
			<input type="text" size="50" name="subject" id="subject" value="" class="required" />
		</div>
							
		<div>
			<label for="message"><strong>Message:</strong></label>
			<textarea rows="5" cols="50" name="message" id="message" class="required"></textarea>
		</div>
	    <input type="submit" value="Send Message" name="submit" />
	</form>
	</div>
</body>
</html>

Open in new window

0
Comment
Question by:Neil_Bradley
7 Comments
 
LVL 3

Accepted Solution

by:
saifikram_md earned 200 total points
ID: 34181095
JQueryvalidation plugin would be a better option. see the link below:-

http://docs.jquery.com/Plugins/validation
0
 
LVL 7

Assisted Solution

by:rgranlund
rgranlund earned 150 total points
ID: 34181189
This is the code I use:  You modify it to suit your needs:

if (preg_match ('/^[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}$/', $trimmed['email'])) {
		if ($trimmed['email1'] == $trimmed['email2']) {
			$e = mysqli_real_escape_string ($dbc, $trimmed['email1']);
		} else {
			echo '<p class="error">Your email did not match the confirmed email!</p>';
		}
	} else {
		echo '<p class="error">Please enter a valid email!</p>';
	}

<form>
<b>email:</b> <input type="email" name="email1" size="20" maxlength="20" />
	
<b>ConfirmEmail:</b> <input type="email" name="email2" />
</form>

Open in new window

0
 
LVL 5

Author Comment

by:Neil_Bradley
ID: 34181221
Ok saifikram_md. I found you link usefull.

using the link you sent me I have setup the same form however I am still drawing a blank when it comes to validating that my second email address is matches the first.

New form shown in my code snippet..
<?php
if(isset($_POST['submit'])) {
$value = test;
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<style type="text/css">
* { font-family: Verdana; font-size: 96%; }
label { width: 10em; float: left; }
label.error { float: none; color: red; padding-left: .5em; vertical-align: top; }
p { clear: both; }
.submit { margin-left: 12em; }
em { font-weight: bold; padding-right: 1em; vertical-align: top; }
</style>
  <script>
  $(document).ready(function(){
    $("#commentForm").validate();
  });
  </script>
  
</head>
<body>
  
<?php echo $value; ?>
 <form class="cmxform" id="commentForm" method="post" action="">
<fieldset>
   <legend>A simple comment form with submit validation and default messages</legend>
   <p>
     <label for="cname">Name</label>
     <em>*</em><input id="cname" name="name" size="25" class="required" minlength="2" />
   </p>
   <p>
     <label for="cemail">E-Mail</label>
     <em>*</em><input id="cemail" name="email" size="25"  class="required email" />
   </p>
    <p>
     <label for="cemail">Re enter Email:</label>
     <em>*</em><input id="cemail" name="email" size="25"  class="required email" />
   </p>
   <p>
     <label for="ccomment">Your comment</label>
     <em>*</em><textarea id="ccomment" name="comment" cols="22"  class="required"></textarea>
   </p>
   <p>
     <input name="submit" type="submit" class="submit" id="submit" value="Submit"/>
   </p>
 </fieldset>
 </form>
</body>
</html>

Open in new window

0
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
LVL 7

Expert Comment

by:rgranlund
ID: 34181340
The two email inputs need to have unique names that match the names in the validation process.
Does this help?


<label for="cemail">E-Mail</label>
     <em>*</em><input id="cemail" name="email1" size="25"  class="required email" />
   </p>
    <p>
     <label for="cemail">Re enter Email:</label>
     <em>*</em><input id="cemail" name="email2" size="25"  class="required email" />
   </p>

Open in new window

0
 
LVL 5

Author Comment

by:Neil_Bradley
ID: 34181347
Solved.
I used the link you sent me saifikram_md however modification was required to achieve what I wanted.
I had to use "rules" to make my script validate another form field entry..
I have added the full working code as a snippet so others who need a similar function can see how it works.
Cheers,
N

PS: rgranlund thanks for the PHP code. It didnt answer my quetion however id did help get me there..
<?php
if(isset($_POST['submit'])) {
$value = test;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>jQuery validation plug-in - main demo</title>

<link rel="stylesheet" type="text/css" media="screen" href="css/screen.css" />

<script src="../lib/jquery.js" type="text/javascript"></script>
<script src="../jquery.validate.js" type="text/javascript"></script>

<script type="text/javascript">

$().ready(function() {

	// validate signup form on keyup and submit
	$("#signupForm").validate({
		rules: {
			firstname: "required",
			lastname: "required",
			
			email: {
				required: true,
				email: true
			},
			confirm_email: {
				required: "true",
				equalTo: "#email"
			},

		},
		messages: {
			firstname: "Please enter your firstname",
			lastname: "Please enter your lastname",
		
			confirm_email: {
				required: "Please confirm email ",
				equalTo: "Please check your email address"
			},
		
		}
	});
	
});
</script>

<style type="text/css">
#commentForm { width: 500px; }
#commentForm label { width: 250px; }
#commentForm label.error, #commentForm input.submit { margin-left: 253px; }
#signupForm { width: 670px; }
#signupForm label.error {
	margin-left: 10px;
	width: auto;
	display: inline;
}
#newsletter_topics label.error {
	display: none;
	margin-left: 103px;
}
</style>

</head>
<body>

<h1 id="banner"><?php echo $value;?></h1>
<div id="main">
  <form action="validate.php" method="post" name="signupForm" class="cmxform" id="signupForm">
<fieldset>
		<legend>Validating a complete form</legend>
		<p>
			<label for="firstname">Firstname</label>
			<input id="firstname" name="firstname" />
		</p>
		<p>
			<label for="lastname">Lastname</label>
			<input id="lastname" name="lastname" />
		</p>
		<p>
			<label for="email">Email</label>
			<input id="email" name="email" />
		</p>
			<p>
			<label for="email">Confirm Email</label>
			<input id="confirm_email" name="confirm_email" />
	</p>
            <p>
			<input name="submit" type="submit" class="submit" id="submit" value="Submit"/>
		</p>
	</fieldset>
</form>

</div>

</body>
</html>

Open in new window

0
 
LVL 82

Assisted Solution

by:hielo
hielo earned 150 total points
ID: 34184179
On your ORIGINAL post, since you are already making sure that $_POST['email'] has a valid email format, then you did NOT need these:
//Check to make sure sure that the entered valu is the same as the entered email address
	if(trim($_POST['confirm_email']) == '')  {
		$hasError = true;
	} else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['confirm_email']))) {
		$hasError = true;
	} else if (trim($_POST['confirm_email']) !== $email)  {
		$hasError = true;
	} else {
		$confirm_email = trim($_POST['confirm_email']);
	}

since you are simply setting $hasError to true or false. You would need that if you were giving specific error messages as to what error actually ocurred! So, in your case you have just gotten rid of the lines I outlined above and the in you else clause if your email check you could have used:

else {
		$email = trim($_POST['email']);
                $hasError = ( $email==trim($_POST['confirm_email']) );
	}

Open in new window

0
 
LVL 5

Author Closing Comment

by:Neil_Bradley
ID: 34184222
Thanks for all of your comments and input. No one answer solved the problem however they all lead me to the solution.
Thanks,
N
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction JSON is an acronym for JavaScript Object Notation.  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.  Similar in concept to XML, but more e…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

773 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question