Validate a HTML Contact Form - php

I have a HTML Contact Form which I need validating in a certain way.
Instead of alerting the user in JavaScript if any fields have not been filled I prefer to show the words 'Field Required' below the fields which were left empty.
Here is my contact form contact.html:
<form id = "myForm" action="contact.php" method="post">
<label for="name">Name:</label>
<input type="text" name="name" id="name" value="" tabindex="1" />
<label for="name">Email:</label>
<input type="text" name="email" id="email" value="" tabindex="1" />
<input type="submit" value="Submit" class="button" />
</form>
Here is my PHP form contact.php (Everything omitted apart from validation):
//Validation... I am building up an error message string to alert the user at the end (omitted)
$errormessage = '';
if(!isset($_POST['name']) || strlen($_POST['name']) < 1){
$errormessage .= 'You have not entered your Name\n';
}
if(!isset($_POST['email']) || strlen($_POST['email']) < 1){
$errormessage .= 'You have not entered your Email Address\n';
}
if($errormessage != ''){ ?>
<script language="javascript" type="text/javascript">
alert('<?php echo "$errormessage" ?>');
window.location = 'contact.html';
</script>
<?php }
else {
$mail_to = 'info#email.co.uk';
$subject = 'Message from a site visitor '.$field_name;
$body_message = 'From: '.$field_name."\n\n";
$body_message .= 'E-mail: '.$field_email."\n\n";
$headers = 'From: '.$field_email."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
}
As you can see my current validation builds up a string in PHP which is going to be alerted to the user at the end (omitted) however I want to replace this method by showing the string 'Field Required' below the HTML fields which have been left empty.

Another option if you are okay using some html5 features is to set the required attribute on the inputs.
required
This attribute specifies that the user must fill in a value before submitting a form. It cannot be used when the type attribute is hidden, image, or a button type (submit, reset, or button). The :optional and :required CSS pseudo-classes will be applied to the field as appropriate.
Taken from https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input
So your html would become:
<form id = "myForm" action="contact.php" method="post">
<label for="name">Name:</label>
<input type="text" name="name" id="name" value="" tabindex="1" required />
<label for="name">Email:</label>
<input type="text" name="email" id="email" value="" tabindex="1" required />
<input type="submit" value="Submit" class="button" />
</form>

I wanted to answer your question without deviating from your approach.
If contact.html can be parsed by php, or it were simply changed to contactform.php, you could send a query string to it indicating which fields had errors and display a message below them.
contactform.php
<form id = "myForm" action="contact.php" method="post">
<label for="name">Name:</label>
<input type="text" name="name" id="name" value="" tabindex="1" />
<?php if (isset($_GET['name']) && $_GET['name'] == 1) {
echo '<br/>This field is required.';
} ?>
<label for="name">Email:</label>
<input type="text" name="email" id="email" value="" tabindex="1" />
<?php if (isset($_GET['email']) && $_GET['email'] == 1) {
echo '<br/>This field is required.';
} ?>
contact.php
$error = FALSE;
$errors = array();
if(!isset($_POST['name']) || strlen($_POST['name']) < 1){
$error = TRUE;
$errors[] = 'name=1';
}
if(!isset($_POST['email']) || strlen($_POST['email']) < 1){
$error = TRUE;
$errors[] = 'email=1';
}
$geterrors = (count($errors) > 1 ? implode('&',$errors) : $errors[0]);
if($error){ ?>
<script language="javascript" type="text/javascript">
window.location = 'contactform.php?<?php echo $geterrors; ?>';
</script>
...

Related

PHP/HTML form post to email not posting data through

I can't get this HTML form to post the data to PHP. The mail comes through ok, and has the titles (i.e. First Name: or Last Name:) but the actual data submitted is blank. What could be wrong with it?
HTML FORM DATA:
<div class="col-md-4 col-sm-12">
<div class="contact-form bottom">
<a name="contact" class="more scrolly"></a>
<h2>We'll call you back!</h2>
<form id="main-contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="form-group">
<input type="text" name="first" class="form-control" required placeholder="First Name">
</div>
<div class="form-group">
<input type="text" name="last" class="form-control" required placeholder="Last Name">
</div>
<div class="form-group">
<input type="tel" name="phone" class="form-control" required placeholder="Phone Number">
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" required placeholder="Email">
</div>
<div class="form-group">
<select input type="text" name="debt" class="form-control">
<option value="Debt_Level">Debt Level</option>
<option value="-">-</option>
<option value="3000-5000">£3000-£5000</option>
<option value="6000-1000">£6000-£10,000</option>
<option value="11000+">£11,000+</option>
</select>
</div>
<div class="form-group">
<input type="occupancy" name="occupancy" class="form-control" required placeholder="Occupancy">
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-submit" value="Submit">
</div>
</form>
</div>
</div>
PHP FORM DATA:
<?php
// if(!isset($_POST['submit']))
if(!empty($_POST['first']) && !empty($_POST['last']) && !empty($_POST['phone']) && !empty($_POST['email']) && !empty($_POST['purpose']) && !empty($_POST['amount']) && !empty($_POST['mortgage']))
{
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!";
}
$first = $_POST['first'];
$last = $_POST['last'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$debt = $_POST['debt'] ;
$occupancy = $_POST['occupancy'] ;
$email_from = 'trustmoney.co.uk';//<== update the email address
$email_subject = "Landing Page App'";
$email_body = "You have received a new application request from: $email \n".
"First Name:” $first “\n".
"Last Name: “$last “\n".
"Telephone: “$phone “\n".
"Email: “$email “\n".
"Debt Amount:”$debt “\n".
"Occupancy: “$occupancy “\n".
"\n".
"\n".
"Sent from trustmoney.co.uk to: “\n".
$to = "matt.mckracken#trustmoney.co.uk \n";//<== update the email address
$headers = "From: $email_from";
//$headers .= "Reply-To: $email ";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
?>
The logic of you PHP doesn't really make sense. As #Epodax has pointed out you are checking if the input value aren't empty, then outputting an error saying they are but the email code is not even inside the IF function.
Your strings where you output the data aren't concatenated properly either.
$email_body = echo "You have received a new application request from:".$email."\n".
"First Name:".$first."\n".
"Last Name: "$last "\n". REST_OF_CODE_HERE
A better structure for managing your form validation would be breaking it down for the user and returning them to the form with appropriate errors.
Something like
$_SESSION['POST_VARS'] = $_POST;
$errors = 0;
if(empty($_POST['first'])) {
$_SESSION['errorFirst'] = "Cannot Be Blank, Contain Numbers or Special Characters";
$errors++;
}
if(empty($_POST['last'])) {
$_SESSION['errorLast'] = "Cannot Be Blank, Contain Numbers or Special Characters";
$errors++;
}
Then count the errors
if($errors == 0) {
// Your Submit Email Code
} else {
require( "YOUR_FORM_HERE.php" );
}
Then you can just output the correct session variable in your form with the appropriate error displayed
if(isset($_SESSION['errorFirst'])) { echo "<div class=\"validateError\">" . $_SESSION['errorFirst'] . "</div>"; unset($_SESSION['errorFirst']); };
Also you can return the users original values to the form so they don't have to start from scratch.
<input type="text" name="first" class="form-control" value="<?php if(!empty($_SESSION['POST_VARS']['first'])) { echo $_SESSION['POST_VARS']['first']; }; ?>"/>
Using this method you'll be able to output all the errors in your form to you users.
There is an error in your logic implementation.You Should use an || instead of && as follows
if(empty($_POST['first']) || empty($_POST['last']) || empty($_POST['phone']) || empty($_POST['email']) || empty($_POST['purpose']) || empty($_POST['amount']) || empty($_POST['mortgage']))
{
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!";
}

jQuery.post not POSTing

I am trying to use jQuery to post data to an emailus.php script.
Here is the script part:
<script>
jQuery(document).ready(function(){
jQuery('#submitt').click(function(){
jQuery.post("/emailus.php", jQuery("#mycontactform").serialize(), function(response) {
jQuery('#success').html(response);
});
return false;
});
});
</script>
and here is the HTML used:
<form action="" method="get" id="mycontactform" >
<label for="name">Your Name:</label><br />
<input type="text" name="name" class="cleann" /><br />
<label for="email">Your Email:</label><br />
<input type="text" name="email" class="cleann" /><br />
<label for="message">Your Message:</label><br />
<textarea name="message" class="cleann" rows="7"></textarea><br />
<input type="button" value="send" id="submitt" class="cleannsubmit" /><div id="success" style="color:green;"></div>
</form>
and here is the php script:
<?php
// Here we get all the information from the fields sent over by the form.
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = 'nohanada#gmail.com';
$subject = 'Fortrove Contact';
$message = 'FROM: '.$name.' Email: '.$email.'Message: '.$message.'\n\nItem:'.$itemname;
print_r($_POST);
if($name && $email && $message){
if (eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
mail($to, $subject, $message);
echo "Your email was sent!";
}
else echo "<span style='color:red'>Invalid email format.</span>";
}
else echo "<span style='color:red'>Please fill all fields</span>";
?>
Problem is that it does not POST the actual fields to the php script. What am i doing wrong?
you have placed the mycontactform inside product_addtocart_form that is the reason which is not allowed so the browser seems to be remocing the mycontactform

How to fix jQuery/PHP form submission?

I am updating a client site and the simple contact form that used to work is now broken. It appears that the HTML form sends and receives data from the jQuery file as I get the error messages returned, though it is not passing the data through to the PHP file for sending an email. If I send the data direct from the HTML form to the PHP file, then an email is sent. The error is probably at the end of the jQuery, though my search for how to fix has not revealed an answer. Any ideas on how to make this work?
HTML Form
<form id="rsForm" action="#" onsubmit="return goContact(this);" name="rsForm">
<input id="formNam" type="hidden" name="formNam" value="3" />
<div class="CU_row">
<div class="CU_form_title"><label for="firstName">First Name:</label></div>
<div class="CU_form_entry"><input id="firstName" maxlength="120" size="39" name="first" type="text" /> <span class="redT">*</span></div>
</div>
<div class="CU_row">
<div class="CU_form_title"><label for="lastName">Last Name:</label></div>
<div class="CU_form_entry"><input id="lastName" maxlength="120" size="39" name="last" type="text" /> <span class="redT">*</span></div>
</div>
<div class="CU_row">
<div class="CU_form_title"><label for="emailAddress">Email:</label></div>
<div class="CU_form_entry"><input id="emailAddress" maxlength="120" size="39" name="email" type="text" /> <span class="redT">*</span></div>
</div>
<div class="CU_row">
<div class="CU_form_title"><label for="subjectLine">Subject:</label></div>
<div class="CU_form_entry"><input id="subjectLine" maxlength="120" size="39" name="subject" type="text" /> <span class="redT">*</span></div>
</div>
<div class="CU_row">
<div class="CU_form_title"><label for="messageCopy">Message:</label></div>
<div class="CU_form_entry"><textarea id="messageCopy" rows="6" cols="30" name="message"></textarea> <span class="redT">*</span></div>
</div>
<div id="CU_reset"><input type="reset" value="Reset" /></div>
<div id="CU_submit"><input type="submit" name="Submit" value="Submit" /></div>
jQuery File
// JavaScript Document
function goContact(theForm){
//Validate the forms and create the array to send.
var frmName = theForm.formNam.value;
//Validate Common elements.
if(theForm.firstName.value.length < 1){
alert("You must supply a First Name");
theForm.firstName.focus();
return false;
}
if(theForm.lastName.value.length < 1){
alert("You must supply a Last Name");
theForm.lastName.focus();
return false;
}
if(theForm.email.value.length < 1){
alert("You must supply an Email");
theForm.email.focus();
return false;
}
if(theForm.subjectLine.value.length < 1){
alert("You must supply a Subject");
theForm.subjectLine.focus();
return false;
}
if(theForm.messageCopy.value.length < 1){
alert("You must supply a Message");
theForm.messageCopy.focus();
return false;
}
sendAjaxReq($(theForm).serialize(true));
return false;
}
function showResult(messageText){
//Show the pop up with the confirmation.
$('msgWindow').innerHTML = messageText;
$('rsForm').reset();
$('frmInter').hide();
}
function sendAjaxReq(formEms){
//Send he ajax request
var rSp = new Ajax.Request("includes/sendContact.php", {
method: 'get',
parameters: formEms,
onComplete: receiveRespon});
}
function receiveRespon(oReq, JSONRsp){
//Receive the response from the ajax request.\
var result = JSONRsp;
if(result){
showResult(result);
}
}
PHP File
<?php
if(isset($_GET['Submit'])){
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: no-reply#sitename.com' . "\r\n";
'X-Mailer: PHP/' . phpversion();
$to = "info#sitename.com";
$subject = "Inquiry from " . $_SERVER['HTTP_HOST'];
$message = "A client has sent a contact us email\n\n";
foreach($_GET AS $field => $value) {
$message .= "field = $field, value = $value \n\n";
}
$mailSent = mail($to, $subject, $message, $headers);
$arr = "Your message has been received.";
header('X-JSON: ('.json_encode($arr).')');
}
?>

HTML form disapearing after Error/Email is sent (PHP)

weird problem here, my html form disapears from the page when I click the send button regardless of success or not.
I display an alert box to indicate if the email was sent or not.
here is the code
<?php
$action = $_REQUEST['action'];
if ($action == "") /* display the contact form */ {
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
<input class="champTextFormulaire" placeholder="Votre Nom" name="name" type="text" value="" size="30"/><br>
<input class="champTextFormulaire" placeholder="Votre email" name="email" type="text" value="" size="30"/><br>
<textarea id="champMessage" placeholder="Votre Message..." name="message" rows="7" cols="30"></textarea><br>
<input class="btnEnvoiFormulaire" type="submit" value="Envoi"/>
</form>
<?php
} else /* send the submitted data */ {
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
if (($name == "") || ($email == "") || ($message == "")) {
print '<script type="text/javascript">';
print 'alert("Veuillez remplir tout les champs")';
print '</script>';
} else {
$from = "From: $name<$email>\r\nReturn-path: $email";
$subject = "Message sent using your contact form";
mail(desiletsmathieu#gmail.com", $subject, $message, $from);
print '<script type="text/javascript">';
print 'alert("Mail envoyé")';
print '</script>';
}
}
}
?>
This is happening because you are using $_REQUEST['action']
After your are submitting the form, your hidden field action becomes $_REQUEST['action'];
And after you submit the form, you get $action = $_REQUEST['action']; to be submit.
Where as you should have a blank value for $_REQUEST['action'] to display the form.
Solution:
1) Either, modify if ($action == "submit")
2) Or, assign blank value to the action (hidden) field
Try it this way.
First off, you forgot a double quote just after mail( that read like this:
mail(desiletsmathieu#gmail.com", $subject, $message, $from);
and needed to be changed to:
mail("desiletsmathieu#gmail.com", $subject, $message, $from);
Plus enctype="multipart/form-data" is for file attachments/uploading so you don't need that.
I also removed this line, which was no longer required:
<input type="hidden" name="action" value="submit">
This works and tested:
Note: I added a name to your submit button in order to give it an extra condition. Plus, you basically had your conditions already set, it just needed to be reworked/rethinked and using less code to achieve the same result.
<form action="" method="POST">
<input class="champTextFormulaire" placeholder="Votre Nom" name="name" type="text" value="" size="30"/><br>
<input class="champTextFormulaire" placeholder="Votre email" name="email" type="text" value="" size="30"/><br>
<textarea id="champMessage" placeholder="Votre Message..." name="message" rows="7" cols="30"></textarea><br>
<input class="btnEnvoiFormulaire" type="submit" name="submit" value="Envoi"/>
</form>
<?php
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$message=$_REQUEST['message'];
if (isset($_POST['submit'])) {
if (($name=="")||($email=="")||($message==""))
{
print '<script type="text/javascript">';
print 'alert("Veuillez remplir tout les champs")';
print '</script>';
exit;
}
else
{
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Message sent using your contact form";
mail("desiletsmathieu#gmail.com", $subject, $message, $from);
print '<script type="text/javascript">';
print 'alert("Mail envoyé")';
print '</script>';
exit;
}
}
?>

Html5 contact form - issues with javascript and php validation

Before I begin please except my appologises if this is to long, I'm totaly new to Html5 (usually design in Flash)and just getting started. I recently downloaded a free template called Brownie and understand most things but the contact form. It's using Javascript, PHP and Ajax I think. Ive got it kinda workin locally but things aren't working how I want. What I'm trying to do is make it validate fields with error message or success message e.t.c. this is the html form code I have:
<p class="required_info"><span>*</span> Required</p>
<!-- SUCCESS MESSAGE -->
<div class="success_box none"> Email successfully sent. Thank you! </div>
<!-- END SUCCESS MESSAGE -->
<!-- START CONTACT FORM -->
<form action="#" class="contact_form">
<p>
<label for="name">Name <span>*</span></label>
<input type="text" class="inputText" id="name" name="name" placeholder="Please enter your full name" pattern="[a-zA-Z ]+" onkeypress="return alpha(event,letters)" required minlength="5" maxlength="50" onpaste="return false;" tabindex="1"/>
<div class="success_title none"> You've entered your name. </div>
<div class="error_title none">* Please enter your full name. </div>
</p>
<div class="clear"></div>
<p>
<label for="company">Company </label>
<input type="text" class="inputText" id="company" name="company" placeholder="Company Name" minlength="3" maxlength="50" onpaste="return false;" tabindex="2"/>
</p>
<div class="clear"></div>
<p>
<label for="email">E-mail <span>*</span></label>
<input type="text" class="inputText" id="email" name="email" placeholder="Please enter a valid email address" required minlength="5" maxlength="50" onpaste="return false;" tabindex="3"/>
<div class="error_title none">* Please enter a valid email. </div>
</p>
<div class="clear"></div>
<p>
<label for="message">Message <span>*</span></label>
<textarea class="inputTextarea" cols="88" rows="6" id="message" name="message" placeholder="Please enter your message" required tabindex="4"></textarea>
<div class="error_title none">* Please enter your message. </div>
</p>
<div class="clear padding20"></div>
<p class="submit"><input type="reset" class="resetBtn button white" onclick="resetFields()" value="Reset" /> Send </p>
</form>
<!-- END CONTACT FORM -->
<!-- ERROR MESSAGE -->
<div class="error_box none"> Please complete all required fields [ highlighted in red ]. </div>
<!-- END ERROR MESSAGE -->
and this is the javascript code:
$(document).ready(function () {
$('#name').focus(function () {
$(this).removeClass('error_class');
});
$('#email').focus(function () {
$(this).removeClass('error_class');
});
$('#message').focus(function () {
$(this).removeClass('error_class');
});
$('.contact_form').submit(function () {
hasError = false;
if ($('#name').val() == '') {
$('#name').addClass('error_class');
hasError = true;
}
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $('#email').val();
if (emailaddressVal == '') {
$('#email').addClass('error_class');
hasError = true;
}
else if (!emailReg.test(emailaddressVal)) {
$('#email').addClass('error_class');
hasError = true;
}
if ($('#email').val() == '') {
$('#email').addClass('error_class');
hasError = true;
}
if ($('#message').val() == '') {
$('#message').addClass('error_class');
hasError = true;
}
if (hasError == true) {
$('.info_box').hide();
$('.error_box').show();
$('.error_title').show();
}
else {
$.ajax({
type: 'POST',
url: 'contact.php',
cache: false,
data: $(".contact_form").serialize(),
success: function (data) {
if (data == "error") {
$('.success_box').hide();
$('.success_title').hide();
$('.error_box').show();
$('.error_title').show();
}
else {
$('.error_box').hide();
$('.error_title').hide();
$('.success_box').show();
$('.success_title').hide();
$('.resetBtn').hide();
$('.submit').hide();
}
}
});
}
return false;
});
});
This is the PHP code:
<?php
$your_email = 'name#domain.com'; // Your email address
$subject = 'Email from your contact form'; // Email subject
$name = isset($_POST['name']) && $_POST['name'] ? $_POST['name'] : ''; // Visitor Name
$company = isset($_POST['company']) && $_POST['company'] ? $_POST['company'] : ''; // Visitor Company
$email = isset($_POST['email']) && $_POST['email'] ? $_POST['email'] : ''; // Visitor Email
$message = isset($_POST['message']) && $_POST['message'] ? $_POST['message'] : ''; // Visitor Message
$website = isset($_POST['website']) && $_POST['website'] ? $_POST['website'] : ''; // Visitor Message
$full_message = 'Website: '.$website. "\r\n\r\n Message:".$message;
if($name && $email && $message)
{
$headers = 'From: '.$name.' <'.$email.'>' . "\r\n" .
'Reply-To: '.$email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$headers .= 'Content-type: text/plain; charset=UTF-8' . "\r\n";
//------------------------------------------------
// Send out email to site admin
//------------------------------------------------
if(#mail($your_email, $subject, $full_message, $headers))
die("success");
else
die("error");
}
else
{
die("error");
}
?>
When the send button is pressed i want it to check if any data has been entered in each input field - if yes add success message if no add error message. I have the error message working but cant get the success message working on individual input fields. Any sugestions would be helpful...
I suspect it is because you are assigning true or false to each variable instead of the value of the variable in your php script. Isset($_POST[test]) is true, not the value of the test form value.

Categories