How to verify an input field using php - php

How can I verify that the contact number a user inputs in the contact form is in fact numbers and they are at least 10 numbers? Meaning I want the input field only accept 10 numbers or more and also accept the plus (+) sign. At the moment the php verifies that the all fields are completed and the email correct.
here is the html code:
<div class="contact-form">
<form id="contact-form" action="sendmail.php" method="post" title="Contact Form" role="form">
<div class="col-sm-6">
<div class="form-group">
<label for="contact-name">Full name</label>
<input type="text" name="name" placeholder="Enter your full name..." class="contact-name" id="contact-name">
</div>
<div class="form-group">
<label for="contact-email">Email</label>
<input type="text" name="email" placeholder="Enter your email..." class="contact-email" id="contact-email">
</div>
<div class="form-group">
<label for="contact-number">Contact number</label>
<input type="text" name="number" class="active" id="contact-number" placeholder="Your contact number...">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="contact-message">Message</label>
<textarea name="message" placeholder="Your message..." class="contact-message" id="contact-message"></textarea>
</div>
</div>
<div class="col-sm-12 text-center">
<button type="submit" class="btn btn-default sketchFlowPrint" id="submit">Send</button>
</div>
</form>
</div>
here is the php code:
<?php
// Email address verification
function isEmail($email) {
return preg_match('|^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]{2,})+$|i', $email);
};
if($_POST) {
// Enter the email where you want to receive the message
$emailTo = 'example#gmail.com';
$clientName = addslashes(trim($_POST['name']));
$clientEmail = addslashes(trim($_POST['email']));
$number = addslashes(trim($_POST['number']));
$message = addslashes(trim($_POST['message']));
$subject = 'Query from My Domain';
$sendMessage = 'Hi' . "\n\n";
$sendMessage .= $message . "\n\n";
$sendMessage .= 'From: ' . $clientName . "\n";
$sendMessage .= 'Email: ' . $clientEmail . "\n";
$sendMessage .= 'Contact number: ' . $number . "\n";
$array = array();
$array['nameMessage'] = '';
$array['emailMessage'] = '';
$array['numberMessage'] = '';
$array['messageMessage'] = '';
if($clientName == '') {
$array['nameMessage'] = 'Please enter your full name.';
}
if(!isEmail($clientEmail)) {
$array['emailMessage'] = 'Please insert a valid email address.';
}
if($number == '') {
$array['numberMessage'] = 'Please enter a valid contact number.';
}
if($message == '') {
$array['messageMessage'] = 'Please enter your message.';
}
if($clientName != '' && isEmail($clientEmail) && $message != '') {
// Send email
$headers = "From: " . $clientName . ' <' . $clientEmail . '>' . "\r\n";
$headers .= PHP_EOL;
$headers .= "MIME-Version: 1.0".PHP_EOL;
$headers .= "Content-Type: multipart/mixed;".PHP_EOL;
$headers .= " boundary=\"boundary_sdfsfsdfs345345sfsgs\"";
mail($emailTo, $subject, $sendMessage, $headers);
}
echo json_encode($array);
} else {
header ('location: index.html#contact');
}
?>
here is the jQuery:
// Contact form
$('.contact-form form').submit(function(e) {
e.preventDefault();
var form = $(this);
var nameLabel = form.find('label[for="contact-name"]');
var emailLabel = form.find('label[for="contact-email"]');
var numberLabel = form.find('label[for="contact-number"]');
var messageLabel = form.find('label[for="contact-message"]');
nameLabel.html('Full name');
emailLabel.html('Email');
numberLabel.html('Contact number');
messageLabel.html('Message');
var postdata = form.serialize();
$.ajax({
type: 'POST',
url: 'sendmail.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.nameMessage !== '') {
nameLabel.append(' - <span class="red error-label"> ' + json.nameMessage + '</span>');
}
if(json.emailMessage !== '') {
emailLabel.append(' - <span class="red error-label"> ' + json.emailMessage + '</span>');
}
if(json.numberMessage !== '') {
numberLabel.append(' - <span class="red error-label"> ' + json.numberMessage + '</span>');
}
if(json.messageMessage !== '') {
messageLabel.append(' - <span class="red error-label"> ' + json.messageMessage + '</span>');
}
if(json.nameMessage === '' && json.emailMessage === '' && json.numberMessage === '' && json.messageMessage === '') {
form.fadeOut('fast', function() {
form.parent('.contact-form').append('<h2 class="text-center"><span class="orange">Thanks for contacting us!</span> We will get back to you very soon.</h2>');
});
}
}
});
});

I'm guessing that the + needs to be the first character (international phone numbers)?
Then this should do it:
if (!preg_match('/^(\+?)+([0-9]{10,})$/', $number)) {
$array['numberMessage'] = 'Please enter a valid contact number.'
}
The plus sign is optional. If it should be required, just remove the ? after the plus sign in the expression.

Check the length is less than 10 or see if the input differs from the filtered input (+ and digits removed).
<?php
function valid_tel($in) {
$valid = true;
if(strlen($in) < 10 || $in !== preg_replace('#[^0-9+]#','', $in)) {
$valid = false;
}
return $valid;
}
var_dump(valid_tel(''));
var_dump(valid_tel('01234'));
var_dump(valid_tel('01234567890')); // 11 long
var_dump(valid_tel('+012345678')); // 10 inc +
var_dump(valid_tel('+0123456'));
var_dump(valid_tel('0123456xyz7890'));
Output:
boolean false
boolean false
boolean true
boolean true
boolean false
boolean false

Related

Refresh page after submit contact form [duplicate]

This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 2 years ago.
Hello guys i already have a problem with my contact form example when i press send email, email is going but the page wont do anything or even it doesnt show succes message, i want the contact form to be cleared after i press submit button.. website
My html code
<div class="col-md-6 col-lg-6 col-sm-12 col-xs-12">
<div class="contact-form mb50 wow fadeIn">
<h2>Send Message</h2>
<form action="process.php" id="contact-form" method="post">
<div class="form-group" id="name-field">
<div class="form-input">
<input type="text" class="form-control" id="form-name" name="form-name" placeholder="Name.." required>
</div>
</div>
<div class="form-group" id="email-field">
<div class="form-input">
<input type="email" class="form-control" id="form-email" name="form-email" placeholder="Email.." required>
</div>
</div>
<div class="form-group" id="phone-field">
<div class="form-input">
<input type="text" class="form-control" id="form-phone" name="form-phone" placeholder="Phone...">
</div>
</div>
<div class="form-group" id="message-field">
<div class="form-input">
<textarea class="form-control" rows="6" id="form-message" name="form-message" placeholder="Your Message Here..." required></textarea>
</div>
</div>
<div class="form-group">
<button type="submit">Send Message</button>
</div>
My process.php code
<?php
// Configure your Subject Prefix and Recipient here
$subjectPrefix = '[Contact Form Website]';
$emailTo = '<info#mywebsite.com>';
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = stripslashes(trim($_POST['name']));
$email = stripslashes(trim($_POST['email']));
$phone = stripslashes(trim($_POST['phone']));
$message = stripslashes(trim($_POST['message']));
if (empty($name)) {
$errors['name'] = 'Name is required.';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Email is invalid.';
}
if (empty($phone)) {
$errors['phone'] = 'Phone is required.';
}
if (empty($message)) {
$errors['message'] = 'Message is required.';
}
// if there are any errors in our errors array, return a success boolean or false
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$subject = "$subjectPrefix $subject";
$body = '
<strong>Name: </strong>'.$name.'<br />
<strong>Email: </strong>'.$email.'<br />
<strong>Phone: </strong>'.$phone.'<br />
<strong>Message: </strong>'.nl2br($message).'<br />
';
$headers = "MIME-Version: 1.1" . PHP_EOL;
$headers .= "Content-type: text/html; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: 8bit" . PHP_EOL;
$headers .= "Date: " . date('r', $_SERVER['REQUEST_TIME']) . PHP_EOL;
$headers .= "Message-ID: <" . $_SERVER['REQUEST_TIME'] . md5($_SERVER['REQUEST_TIME']) . '#' . $_SERVER['SERVER_NAME'] . '>' . PHP_EOL;
$headers .= "From: " . "=?UTF-8?B?".base64_encode($name)."?=" . "<$email>" . PHP_EOL;
$headers .= "Return-Path: $emailTo" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "X-Mailer: PHP/". phpversion() . PHP_EOL;
$headers .= "X-Originating-IP: " . $_SERVER['SERVER_ADDR'] . PHP_EOL;
mail($emailTo, "=?utf-8?B?" . base64_encode($subject) . "?=", $body, $headers);
$data['success'] = true;
$data['message'] = 'Congratulations. Your message has been sent successfully';
}
// return all our data to an AJAX call
echo json_encode($data);
}
My contact-form.js code
(function ($, window, document, undefined) {
'use strict';
var $form = $('#contact-form');
$form.submit(function (e) {
// remove the error class
$('.form-group').removeClass('has-error');
$('.help-block').remove();
// get the form data
var formData = {
'name' : $('input[name="form-name"]').val(),
'email' : $('input[name="form-email"]').val(),
'phone' : $('input[name="form-phone"]').val(),
'message' : $('textarea[name="form-message"]').val()
};
// process the form
$.ajax({
type : 'POST',
url : 'process.php',
data : formData,
dataType : 'json',
encode : true
}).done(function (data) {
// handle errors
if (!data.success) {
if (data.errors.name) {
$('#name-field').addClass('has-error');
$('#name-field').find('.form-input').append('<span class="help-block">' + data.errors.name + '</span>');
}
if (data.errors.email) {
$('#email-field').addClass('has-error');
$('#email-field').find('.form-input').append('<span class="help-block">' + data.errors.email + '</span>');
}
if (data.errors.phone) {
$('#phone-field').addClass('has-error');
$('#phone-field').find('.form-input').append('<span class="help-block">' + data.errors.phone + '</span>');
}
if (data.errors.message) {
$('#message-field').addClass('has-error');
$('#message-field').find('.form-input').append('<span class="help-block">' + data.errors.message + '</span>');
}
} else {
// display success message
$form.html('<div class="alert alert-success">' + data.message + '</div>');
}
}).fail(function (data) {
// for debug
console.log(data)
});
e.preventDefault();
});
}(jQuery, window, document));
Cant you simply add location.reload() in your Js at the end of your function when sending succeeds?
try to add a function in js like that
function myFunction() {
location.replace("https://URL")
}
And then onclick="myFunction()"

validate php contact form with checkbox

I am trying to add another validation to a contact form. I need a checkbox at the bottom of the form which the user check before they can submit the form.
This is what i have so far, which validates the form. I would like to know how to add a checkbox so the form is only submitted if the box is checked
<section class="form wow fadeInRight" data-wow-duration="2s">
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3 contact-form">
<h2>Contact Us</h2>
<p>Please do not hesitate to get in touch with us by filling out the form or using the contact details below</p>
<form class="form-horizontal" action="" id="form" method="post" name="form">
<input type="hidden" name="bts" value="" />
<input type="hidden" name="page" value="<?php echo $current_url; ?>" />
<div class="form-group">
<div class="col-md-12">
<input type="text" class="form-control" id="name" name="name" placeholder="Your Name:*" value="<?php echo $send_data['name']; ?>" required>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input type="email" class="form-control" id="email" name="email" placeholder="Email Address:*" value="<?php echo $send_data['email']; ?>" required>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input type="tel" minlength="10" class="form-control" id="tel" name="tel" placeholder="Contact Number:*" value="<?php echo $send_data['tel']; ?>" required>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<textarea class="form-control" id="message" name="message" placeholder="General Enquiry:" required><?php echo $send_data['message']; ?></textarea>
</div>
</div>
<div class="form-group">
<div class=" col-md-12">
<button type="submit" class="button btn btn-warning">Send</button>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
<?php
$target_page = false;
$send_to = config('company_email');
$company_name = config('company_name');
$errors = array();
$posted = false;
$success = false;
$current_url = (isset($_POST['page']) && !empty($_POST['page'])) ? $_POST['page'] : 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
# is this the normal or quick form?
$quick = (isset($_POST['type']) && $_POST['type'] == 'quick') ? true : false;
# set up the common fields
$send_data = array();
$send_data['name'] = (isset($_POST['name']) && !empty($_POST['name'])) ? $_POST['name'] : '';
$send_data['email'] = (isset($_POST['email']) && !empty($_POST['email'])) ? $_POST['email'] : '';
# if this is not the quick form then add the additional fields
if (!$quick) {
$send_data['tel'] = (isset($_POST['tel']) && !empty($_POST['tel'])) ? $_POST['tel'] : '';
}
$send_data['message'] = (isset($_POST['message']) && !empty($_POST['message']) && $_POST['message'] != ' ') ? $_POST['message'] : '';
# check if the form has been submitted
if (isset($_POST['bts']) && $_POST['bts'] == '') {
# the form has been posted
$posted = true;
# check the name value
if ($send_data['name'] == '') {
$errors[] = 'Please fill in your name';
}
# check the email value
if ($send_data['email'] == '') {
$errors[] = 'Please fill in your email address';
} else {
# validate the email
$validate_email = filter_var($send_data['email'], FILTER_VALIDATE_EMAIL);
if (!$validate_email) {
$errors[] = 'Please check your email address is correct';
} else {
# check the domains MX records
if(!checkdnsrr(array_pop(explode("#",$send_data['email'])),"MX")){
$errors[] = 'Please use a valid email address';
}
}
}
# if this is not the quick form then check the additional fields
if (!$quick) {
if (strlen($send_data['tel']) < 10) {
$errors[] = 'Please add a valid telephone number!';
}
}
# check the message
if ($send_data['message'] == '') {
$errors[] = 'Please fill in a message';
}
# if there are no errors then send the message
if (count($errors) == 0) {
$send_from = $send_data['name'] . "<" . $send_data['email'] . ">";
$subject = 'Enquiry From Website ' . $_SERVER['HTTP_HOST'];
$email_message = 'Below are the details that have been submitted on your contact form' . "\n\n";
$email_message .= '________________________________________' . "\n\n";
if (count($send_data) > 0) {
foreach ($send_data as $key => $value) {
$email_message .= $key . ' : ' . htmlspecialchars($value) . "\n";
}
}
$email_message .= '________________________________________' . "\n\n";
$email_message .= 'IP : ' . $_SERVER["REMOTE_ADDR"] . "\n\n";
$email_message .= 'URL : ' . $current_url . "\n\n";
$email_message .= 'WUKmedia | http://wukmedia.uk';
#$headers = "From: " . strip_tags($send_from) . "\r\n";
#$headers .= "Reply-To: ". strip_tags($_POST['req-email']) . "\r\n";
#$headers .= "MIME-Version: 1.0\r\n";
#$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (mail($send_to, $subject, $email_message, "From: " . $send_from)) {
$success = true;
# now that the enquiry has been sent we can confirm to user
$FromCompany = $company_name . "<" . $send_to . ">";
$thanks_email = "Thank you for your enquiry " . $send_data['name'] . ".\n";
$thanks_email .= "We will be back in touch with you shortly, \n\n";
$thanks_email .= $company_name . "\n";
$thanks_email .= 'http://' . $_SERVER['HTTP_HOST'] . "\n\n\n";
mail($send_data['email'], "Thanks for the Enquiry", $thanks_email, "From: " . $send_from);
# now store the data in a json array
$send_data['ip'] = $_SERVER["REMOTE_ADDR"];
$send_data['timestamp'] = time();
$json_array = "\n" . json_encode($send_data);
$json_file = $_SERVER['DOCUMENT_ROOT'] . '/tp/enquiries/enquiries.json';
file_put_contents($json_file, $json_array, FILE_APPEND | LOCK_EX);
} else {
$errors[] = 'Your enquiry has not been sent, please try again';
}
}
}
$target_page = false;
$send_to = config('company_email');
$company_name = config('company_name');
$errors = array();
$posted = false;
$success = false;
$current_url = (isset($_POST['page']) && !empty($_POST['page'])) ? $_POST['page'] : 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
# is this the normal or quick form?
$quick = (isset($_POST['type']) && $_POST['type'] == 'quick') ? true : false;
# set up the common fields
$send_data = array();
$send_data['name'] = (isset($_POST['name']) && !empty($_POST['name'])) ? $_POST['name'] : '';
$send_data['email'] = (isset($_POST['email']) && !empty($_POST['email'])) ? $_POST['email'] : '';
# if this is not the quick form then add the additional fields
if (!$quick) {
$send_data['tel'] = (isset($_POST['tel']) && !empty($_POST['tel'])) ? $_POST['tel'] : '';
}
$send_data['message'] = (isset($_POST['message']) && !empty($_POST['message']) && $_POST['message'] != ' ') ? $_POST['message'] : '';
# check if the form has been submitted
if (isset($_POST['bts']) && $_POST['bts'] == '') {
# the form has been posted
$posted = true;
# check the name value
if ($send_data['name'] == '') {
$errors[] = 'Please fill in your name';
}
# check the email value
if ($send_data['email'] == '') {
$errors[] = 'Please fill in your email address';
} else {
# validate the email
$validate_email = filter_var($send_data['email'], FILTER_VALIDATE_EMAIL);
if (!$validate_email) {
$errors[] = 'Please check your email address is correct';
} else {
# check the domains MX records
if(!checkdnsrr(array_pop(explode("#",$send_data['email'])),"MX")){
$errors[] = 'Please use a valid email address';
}
}
}
# if this is not the quick form then check the additional fields
if (!$quick) {
if (strlen($send_data['tel']) < 10) {
$errors[] = 'Please add a valid telephone number!';
}
}
# check the message
if ($send_data['message'] == '') {
$errors[] = 'Please fill in a message';
}
# if there are no errors then send the message
if (count($errors) == 0) {
$send_from = $send_data['name'] . "<" . $send_data['email'] . ">";
$subject = 'Enquiry From Website ' . $_SERVER['HTTP_HOST'];
$email_message = 'Below are the details that have been submitted on your contact form' . "\n\n";
$email_message .= '________________________________________' . "\n\n";
if (count($send_data) > 0) {
foreach ($send_data as $key => $value) {
$email_message .= $key . ' : ' . htmlspecialchars($value) . "\n";
}
}
$email_message .= '________________________________________' . "\n\n";
$email_message .= 'IP : ' . $_SERVER["REMOTE_ADDR"] . "\n\n";
$email_message .= 'URL : ' . $current_url . "\n\n";
$email_message .= 'WUKmedia | http://wukmedia.uk';
#$headers = "From: " . strip_tags($send_from) . "\r\n";
#$headers .= "Reply-To: ". strip_tags($_POST['req-email']) . "\r\n";
#$headers .= "MIME-Version: 1.0\r\n";
#$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (mail($send_to, $subject, $email_message, "From: " . $send_from)) {
$success = true;
# now that the enquiry has been sent we can confirm to user
$FromCompany = $company_name . "<" . $send_to . ">";
$thanks_email = "Thank you for your enquiry " . $send_data['name'] . ".\n";
$thanks_email .= "We will be back in touch with you shortly, \n\n";
$thanks_email .= $company_name . "\n";
$thanks_email .= 'http://' . $_SERVER['HTTP_HOST'] . "\n\n\n";
mail($send_data['email'], "Thanks for the Enquiry", $thanks_email, "From: " . $send_from);
# now store the data in a json array
$send_data['ip'] = $_SERVER["REMOTE_ADDR"];
$send_data['timestamp'] = time();
$json_array = "\n" . json_encode($send_data);
$json_file = $_SERVER['DOCUMENT_ROOT'] . '/tp/enquiries/enquiries.json';
file_put_contents($json_file, $json_array, FILE_APPEND | LOCK_EX);
} else {
$errors[] = 'Your enquiry has not been sent, please try again';
}
}
}
just put required on tag checkbox. ex:
<input type="checkbox" name="" value="" required> text
When validating the forms I code, I just use the Recaptcha. Is this an option for you? If it is then you need the site to be live so you have access to the domain name of the site.
To begin this go to: https://www.google.com/recaptcha/intro/v3beta.html
Get a SITEKEY & SECERTKEY - they have step by step (very simple) on how to access these two keys.
Once you have them only a small snippet of code in the head tags like so:
<head>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
After, you just have to add the code into your form tags like so:
<form>
<!-- put this wherever you want it in the form - usually at the bottom -->
<div class="g-recaptcha" data-sitekey="<!-- Site Key HERE -->"></div>
</form>
And then finally just authorise it in your PHP code that handles the form data, for example:
$captcha = $_POST["g-recaptcha-response"]; // Declare variable
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
header("Location: <!-- Error HTML page OR echo and error statement -->");
exit;
}
$secretKey = "<!-- SECRET KEY HERE -->";
$ip = $_SERVER['REMOTE_ADDR'];
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response, true);
if(intval($responseKeys["success"]) !== 1) {
echo '<h2>Spam Detected</h2>';
}
else {
header("Location: <!-- Thank you HTML page OR echo and thanks statement -->");
}
You'll see I've commented where the site & secret key go.

PHP Multiple Validations

I'm trying to make $name, $email, and $message validate in one script without making them all look like a error (make them all a red color) rather than the one that is actually incorrect.
Her is the code I'm using:
PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$visitors_site = $_POST['site'];
$message = $_POST['message'];
$email_from = 'mattmowen1#gmail.com';
$email_subject = 'New Contact Submission';
$to = 'matt.owen#example.com';
$headers = "From:" . $email;
$headers = "Contact Submission From: " . $email;
$message1 = "Name: " . $name;
$message2 = "\n\nEmail: " . $email;
$message3 = "\n\nPhone: " . $phone;
$message4 = "\n\nTheir Site: " . $visitors_site;
$message5 = "\n\nMessage: " . $message;
$email_body = $message1 . $message2 . $message3 . $message4 . $message5;
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
mail($to, $email_subject, $email_body,$headers);
exit(json_encode(array('error' => 0)));
} else {
exit(json_encode(array('error' => 1)));
}
if ($name == "") {
exit(json_encode(array('error' => 1)));
} else {
mail($to, $email_subject, $email_body,$headers);
exit(json_encode(array('error' => 0)));
}
?>
AJAX Script:
var sendEmail = function(){
var url = 'main.php';
$.ajax({
url : url,
type : "POST",
dataType : "JSON",
data : $('#contact-form').serialize(),
success : function(response) {
if (response.error == 0) {
$('#contact-form')[0].reset();
alert('Form submitted successfully. We will contact you asap.');
} else {
$('#email-input').css('color', 'red');
alert('ERROR MESSAGE');
}
}
})
return false;
}
HTML:
<div id="contact">
<div class="container">
<form id="contact-form" method="post" onsubmit="return sendEmail()">
<h1>Contact Form</h1>
<fieldset>
<input placeholder="Your Name" type="text" name="name" id="name-input" required value="<?php echo isset($_POST['name']) ? $_POST['name'] : ''; ?>">
</fieldset>
<fieldset>
<input placeholder="Your Email Address" type="email" name="email" id="email-input" required value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>">
</fieldset>
<fieldset>
<input placeholder="Your Phone Number (optional)" type="tel" name="phone" required>
</fieldset>
<fieldset>
<input placeholder="Your Web Site (optional)" type="url" name="site" required>
</fieldset>
<fieldset>
<textarea placeholder="Type your message here...." name="message" required value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>"></textarea>
</fieldset>
<fieldset>
<button type="submit" id="contact-submit" name="submit">Submit</button>
</fieldset>
</form>
</div>
</div>
Just send back a list of bad elements, instead of a blanket error statement
<?php
// ...
$errors = [];
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = "email";
}
if ($name == "") {
$errors[] = "name";
}
if ($message == "") {
$errors[] = "message";
}
if (count($errors) === 0) {
mail($to, $email_subject, $email_body,$headers);
}
echo json_encode($errors);
//...
Then in your JS:
success : function(response) {
if (response.length == 0) {
$('#contact-form')[0].reset();
alert('Form submitted successfully. We will contact you asap.');
} else {
for (var i = 0; i < response.length; i++) {
$('#' + response[i] + '-input').css('color', 'red');
alert('ERROR MESSAGE');
}
}
}
My Javascript is a bit rusty but that should do the trick.
Note that <textarea> doesn't have a value attribute, contents are added as a child text node. You should also use htmlspecialchars() on all output from PHP to prevent XSS problems.
in your js:
$erro = 0;
if(document.getElementById("name-input").value == null or document.getElementById("name-input").value == ""){
$erro = 1;
document.getElementById("name-input").style.borderColor = "red";
}
if(document.getElementById("email-input").value == null or document.getElementById("email-input").value == ""){
$erro = 1;
document.getElementById("email-input").style.borderColor = "red";
}
...
if($erro == 0){
//run ajax
}
You can put a bit more html code to make a hidden textbox appear using.
if(document.getElementById("email-input").value == null or document.getElementById("email-input").value == ""){
$erro = 1;
document.getElementById("email-input").style.borderColor = "red";
document.getElementById("id_erro1").style.visibility = "visible";
}
create in your html:
<fieldset>
<input placeholder="Your Email Address" type="email" name="email" id="email-input" required value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>">
<input type="hidden" name="error_mensage1" id="id_erro1" value="Required field" >
</fieldset>
Use css to Spice up.

Not receiving all fields in php mail

Here is the mail handler only part being received in sent emails is the actual message missing parts are name and phone.
<?php
session_start();
$email_to = "test#test.com";
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
if(mail($email_to, $subject, $message, $headers)){
echo "success";
}
else{
echo "failed";
}
?>
Here is the html part which I have checked over and over and cant figure out whats wrong
<form id="contact" class="row" name="form1" method="post" action="">
<div class="span2">
<label>Name <span class="req">*</span></label>
<input type="text" class="full" name="name" id="name"/>
<div id="error_name" class="error">Please check your name</div>
</div>
<div class="span2">
<label>Phone <span class="req">*</span></label>
<input type="text" class="full" name="phone" id="phone"/>
<div id="error_phone" class="error">Please check your phone</div>
</div>
<div class="span4">
<label>Email <span class="req">*</span></label>
<input type="text" class="full" name="email" id="email"/>
<div id="error_email" class="error">Please check your email</div>
</div>
<div class="span8">
<label>Message <span class="req">*</span></label>
<textarea cols="8" rows="10" name="message" id="message" class="full"></textarea>
<div id="error_message" class="error">Please check your message</div>
<div id="mail_success" class="success"> Thank you. Your message has been sent.</div>
<div id="mail_failed" class="error">Error, email not sent</div>
<p id="btnsubmit"><input type="submit" id="send" value="Send" class="btn btn-large"/></p>
</div>
</form>
Js script -------------------
$(document).ready(function(){
$("#send").click(function(){
var name = $("#name").val();
var phone = $("#phone").val();
var email = $("#email").val();
var message = $("#message").val();
var error = false;
if (name.length == 0) {
var error = true;
$("#error_name").fadeIn(500);
}
else {
$("#error_name").fadeOut(500);
}
if (phone.length == 0) {
var error = true;
$("#error_phone").fadeIn(500);
}
else {
$("#error_phone").fadeOut(500);
}
if(email.length == 0 || email.indexOf("#") == "-1" || email.indexOf(".") == "-1"){
var error = true;
$("#error_email").fadeIn(500);
}
else {
$("#error_email").fadeOut(500);
}
if(message.length == 0){
var error = true;
$("#error_message").fadeIn(500);
}else{
$("#error_message").fadeOut(500);
}
if(error == false){
$("#send").attr({"disabled" : "true", "value" : "Loading..." });
$.ajax({
type: "POST",
url : "send.php",
data: "name=" + name + "&email=" + email + "&subject=" + "Website Enquiry" + "&message=" + message,
success: function(data){
if(data == 'success'){
$("#btnsubmit").remove();
$("#mail_success").fadeIn(500);
}else{
$("#mail_failed").html(data).fadeIn(500);
$("#send").removeAttr("disabled").attr("value", "send");
}
}
});
}
return false;
});
});
Obviously, you are missing parts!... You simply declare variables, but you didn't include them in the mail itself.
In this example, I'm adding $name and $phone to $message body.
<?php
session_start();
$email_to = "test#test.com";
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'] . "\n";
$message .= "Name: " . $name . "\n";
$message .= "Phone: " . $phone;
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
if(mail($email_to, $subject, $message, $headers)){
echo "success";
}
else{
echo "failed";
}
?>

Having an Issue with a form field on my site

I've got a basic form on my website and have been trying to add in a phone number field.
The header validation is:
//process the contact form
$('#submit-form').click(function(){
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var names = $('#contact-form [name="contact-names"]').val();
var email_address = $('#contact-form [name="contact-email"]').val();
var phone = $('#contact-form [name="phone"]').val();
var comment = $.trim($('#contact-form #message').val());
var data_html ='' ;
if(names == ""){
$('.name-required').html('Please enter your name.');
}else{
$('.name-required').html('');
}
if(phone == ""){
$('.phone-required').html('Please enter your phone number.');
}else{
$('.phone-required').html('');
}
if(email_address == ""){
$('.email-required').html('Your email is required.');
}else if(reg.test(email_address) == false){
$('.email-required').html('Invalid Email Address.');
}else{
$('.email-required').html('');
}
if(comment == ""){
$('.comment-required').html('Comment is required.');
}else{
$('.comment-required').html('');
}
if(comment != "" && names != "" && reg.test(email_address) != false) {
data_html = "names="+ names + "&phone" + phone + "&comment=" + comment + "&email_address="+ email_address;
//alert(data_html);
$.ajax({
type: 'POST',
url: 'php-includes/contact_send.php',
data: data_html,
success: function(msg){
if (msg == 'sent'){
$('#contact-form [name="contact-names"]').val('');
$('#contact-form [name="contact-email"]').val('');
$('#contact-form #contact-phone').val('');
$('#contact-form #message').val('');
$(window.location = "http://theauroraclinic.com/thank-you.html");
}else{
$('#success').html('<div class="error">Mail Error. Please Try Again!</div>') ;
}
}
});
}
return false;
});
});
</script>
The Actual Form is:
<form id="contact-form" method="post" name="contact-form" class="infield rounded-fields form-preset">
<h3>We respect your privacy. </h3>
<h5> Please be assured that we will not share any information without your prior consent.</h5>
<p><span class="note">All fields are required!</span>
<p><label for="name">Name</label>
<input class="text" name="contact-names" type="text" id="name" />
<span class="name-required"></span></p>
<p><label for="email">Email</label>
<input class="text" name="contact-email" type="text" id="email" />
<span class="email-required"></span></p>
<p><label for="phone">Phone</label>
<input class="text" name="contact-phone" type="text" id="phone" />
<span class="phone-required"></span></p>
<p><label for="message" class="message-label">Message</label>
<textarea class="text-area" name="contact-comment" id="message"></textarea>
<span class="comment-required"></span></p>
<p><input class="send" id="submit-form" name="submit" type="submit" value="Send" /></p>
</form>
And the form processing php file is:
<?php
$names = $_POST['names'];
$email = $_POST['email_address'];
$phone = $_POST['phone'];
$comment = $_POST['comment'];
$to ='name#email.com';
$message = "";
$message .= "*Name: " . htmlspecialchars($names, ENT_QUOTES) . "<br>\n";
$message .= "*Email: " . htmlspecialchars($email, ENT_QUOTES) . "<br>\n";
$message .= "*Phone: " . htmlspecialchars($phone, ENT_QUOTES) . "<br>\n";
$message .= "Comment: " . htmlspecialchars($comment, ENT_QUOTES) . "<br>\n";
$lowmsg = strtolower($message);
$headers = "MIME-Version: 1.0\r\nContent-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: \"" . $names . "\" <" . $email . ">\r\n";
$headers .= "Reply-To: " . $email . "\r\n";
$message = utf8_decode($message); mail($to, "Note from the Contact Form", $message, $headers);
if ($message){
echo 'sent';
}else{
echo 'failed';
}
?>
The form still works fine, but it won't pass any input into the phone number field. I did add in the redirect on submission. It's weird that that would only affect 1 field though. Any help would be great, I'm not that good at js a& php!
The phone field is named contact-phone not phone
In the javascript, [name="phone"] should be changed to [name="contact-phone"].
data_html = "names="+ names + "&phone" + phone + "&comment=" + comment + "&email_address="+ email_address;
change this... &phone= is missing
data_html = "names="+ names + "&phone=" + phone + "&comment=" + comment + "&email_address="+ email_address;

Categories