/    Sign up×
Community /Pin to ProfileBookmark

Javascript validate human field for contact form

I have tried getting my contact form to work trying to update the php – with no success. I now think I should be able to get this to work by updating the JS, but of course I know about as much JS as I do PHP!

So here we go again…

I have a contact form I am using in a Bootstrap responsive single-page site. The form works just fine and sends the emails just fine. My site does not get a whole lot of traffic and I dislike the Captcha fields, so I wanted to insert a simple field for users to enter to ensure they are human. I added a simple math question. Now, I need to know how to validate that the user entered the correct math answer before the email is processed.

My form uses a contact_me.js file in combination with the jqBootstrapBalidation.js file to validate and send the form to the contact_me.php to process the email. I tried updating the PHP (with some suggestions from here) but I could not get it to work. It will always send the email through even if the math answer was entered incorrectly.

It is important to note that I did not write the code for this, I am very new to js. The form and code was supplied by startbootstrap.com templates.

Looking at the contact_me.js field, I can see that it starts off validating the fields with the jqBootstrapBalidation.js. I see it then moves down to a preventDefault and has a comment stating “prevent spam click and default submit behaviour. Is this code already preventing SPAM emails here?

If it is not, I want to force the user to input the correct answer to the math question. I added this field myself. I added the variable for the human field to the contact_me.js file (I assume I needed to do this) to get the value from the form.

Further down on the .js file it then uses ajax to post to the contact_me.php to process the email. Below this is where it looks like it further validates the fields and displays the success/error messages. Is there someplace here I can verify if the user entered the correct math equation (answer should be =5) and if it is correct, then to process the email via the contact_me.php and if the answer is incorrect then to display an error message without sending to the php and ask to try again? Below is the html, contact_me.js and the contact_me.php. Thank you so much for your help with this!

HTML:

[code=html]<form name=”sentMessage” id=”contactForm” novalidate>
<div class=”row control-group”>
<div class=”form-group col-xs-12 floating-label-form-group controls”>
<label>Name</label>
<input type=”text” class=”form-control” placeholder=”Name” id=”name” required data-validation-required-message=”Please enter your name.”>
<p class=”help-block text-danger”></p>
</div>
</div>
<div class=”row control-group”>
<div class=”form-group col-xs-12 floating-label-form-group controls”>
<label>Email Address</label>
<input type=”email” class=”form-control” placeholder=”Email Address” id=”email” required data-validation-required-message=”Please enter your email address.”>
<p class=”help-block text-danger”></p>
</div>
</div>
<div class=”row control-group”>
<div class=”form-group col-xs-12 floating-label-form-group controls”>
<label>Phone Number</label>
<input type=”tel” class=”form-control” placeholder=”Phone Number” id=”phone” required data-validation-required-message=”Please enter your phone number.”>
<p class=”help-block text-danger”></p>
</div>
</div>
<div class=”row control-group”>
<div class=”form-group col-xs-12 floating-label-form-group controls”>
<label>Message</label>
<textarea rows=”5″ class=”form-control” placeholder=”Message” id=”message” required data-validation-required-message=”Please enter a message.”></textarea>
<p class=”help-block text-danger”></p>
</div>
</div>
<div class=”row control-group”>
<div class=”form-group col-xs-12 floating-label-form-group controls”>
<label>Human</label>
<input type=”text” class=”form-control” placeholder=”Two + 3 = ?” id=”human” required data-validation-required-message=”Please solve math equation to prove you are human”>
<p class=”help-block text-danger”></p>
</div>
</div>
<br>
<div id=”success”></div>
<div class=”row”>
<div class=”form-group col-xs-12″>
<button type=”submit” class=”btn btn-success btn-lg”>Send</button>
</div>
</div>
</form>[/code]

contact_me.js:

[CODE]$(function() {

$(“input,textarea”).jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
// Prevent spam click and default submit behaviour
$(“#btnSubmit”).attr(“disabled”, true);
event.preventDefault();

// get values from FORM
var name = $(“input#name”).val();
var email = $(“input#email”).val();
var phone = $(“input#phone”).val();
var message = $(“textarea#message”).val();
var human = $(“textarea#human”).val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(‘ ‘) >= 0) {
firstName = name.split(‘ ‘).slice(0, -1).join(‘ ‘);
}
$.ajax({
url: “././mail/contact_me.php”,
type: “POST”,
data: {
name: name,
phone: phone,
email: email,
message: message,
human: human
},
cache: false,
success: function() {
// Enable button & show success message
$(“#btnSubmit”).attr(“disabled”, false);
$(‘#success’).html(“<div class=’alert alert-success’>”);
$(‘#success > .alert-success’).html(“<button type=’button’ class=’close’ data-dismiss=’alert’ aria-hidden=’true’>&times;”)
.append(“</button>”);
$(‘#success > .alert-success’)
.append(“<strong>Your message has been sent. </strong>”);
$(‘#success > .alert-success’)
.append(‘</div>’);

//clear all fields
$(‘#contactForm’).trigger(“reset”);
},
error: function() {
// Fail message
$(‘#success’).html(“<div class=’alert alert-danger’>”);
$(‘#success > .alert-danger’).html(“<button type=’button’ class=’close’ data-dismiss=’alert’ aria-hidden=’true’>&times;”)
.append(“</button>”);
$(‘#success > .alert-danger’).append(“<strong>Sorry ” + firstName + “, it seems that my mail server is not responding. Please try again later!”);
$(‘#success > .alert-danger’).append(‘</div>’);
//clear all fields
$(‘#contactForm’).trigger(“reset”);
},
})
},
filter: function() {
return $(this).is(“:visible”);
},
});

$(“a[data-toggle=”tab”]”).click(function(e) {
e.preventDefault();
$(this).tab(“show”);
});
});

// When clicking on Full hide fail/success boxes
$(‘#name’).focus(function() {
$(‘#success’).html(”);
});[/CODE]

contact_me.php:

[code=php]<?php
// Check for empty fields
if(empty($_POST[‘name’]) ||
empty($_POST[’email’]) ||
empty($_POST[‘phone’]) ||
empty($_POST[‘message’]) ||
empty($_POST[‘human’]) ||
!filter_var($_POST[’email’],FILTER_VALIDATE_EMAIL))
{
echo “No arguments Provided!”;
return false;
}

//Check if simple anti-bot test is correct
if ($human !== 5) {
$errHuman = ‘Your anti-spam is incorrect’;
}

$name = $_POST[‘name’];
$email_address = $_POST[’email’];
$phone = $_POST[‘phone’];
$message = $_POST[‘message’];
$message = $_POST[‘human’];

// Create the email and send the message
$to = ‘[email protected]’; // Add your email address inbetween the ” replacing [email protected] – This is where the form will send a message to.
$email_subject = “Portfolio Website Message: $name”;
$email_body = “You have received a new message from your portfolio website contact form.nn”.”Here are the details:nnName: $namennEmail: $email_addressnnPhone: $phonennMessage:n$message”;
$headers = “From: [email protected]”; // This is the email address the generated message will be from. We recommend using something like [email protected].
$headers .= “Reply-To: $email_address”;
mail($to,$email_subject,$email_body,$headers);
return true;
?>[/code]

to post a comment
JavaScript

0Be the first to comment 😎

×

Success!

Help @rexmiller1122 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...