I have a problem with the validation of the content entered into a contact form.
Here’s the form:
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$(document).ready(function(){
$('#contact_messenbrinkeu').ajaxForm(
function(){
alert("Your message has been send!");
}
)
})
</script>
</head>
<body>
<section id="page">
<?php include("includes/header.php"); ?>
<section id="articles">
<article id="article1">
<div id="contact-form">
<form id="contact_messenbrinkeu" action="sendform.php" method="post">
<fieldset id="form">
<label for="name">Name*</label><br>
<input type="text" name="name" placeholder="Your Name"title="enter your name" class="alpha required"><br>
<label for="email">E-mail*</label><br>
<input type="email" name="email" placeholder="mail@example.com" title="Enter your e-mail address" class="mail required"><br>
<label for="phone">Phone</label><br>
<input type="text" name="phone" placeholder="00 45 12 34 56 78" class="numeric"><br>
<label for="website">Website</label><br>
<input type="text" name="website" placeholder="www.example.com" id="website"><br>
<label for="message">Message*</label><br id="message">
<textarea name="message" class="required"></textarea>
</fieldset>
<fieldset id="button">
<button type="submit">>> Send</button>
<button type="reset">reset <<</button>
</fieldset>
</form>
</div><!-- /end #contact-form -->
</article><!-- Article 1 end -->
</section>
<?php include("includes/jquery.php");?>
<script type="text/javascript">
/*<![CDATA[*/
jQuery.noConflict();
jQuery(document).ready(function($){
// when submit button is pressed
$("#contact_messenbrinkeu").submit(function() {
var pass = true;
var errors = {
required : 'this field is required',
email : 'enter a valid email address',
numeric : 'enter a number without spaces, dots or commas',
alpha : 'this field accepts only letters & spaces'
};
var tests = {
email : /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/,
numeric : /^[0-9]+$/,
alpha : /^[a-zA-Z ]+$/
};
// clear error messages
$(".error").removeClass();
$(".error-message").remove();
function displayError(el, type) {
$(el).parent().addClass("error").find('label').append('<span class=\"error-message\"> – ' + errors[type] + '</span>');
}
$('.required, .email, .numeric, .alpha').each(function(){
var value = $(this).val();
var valueExists = value.length === 0 ? false : true;
var required = $(this).hasClass('required');
var email = $(this).hasClass('email');
var numeric = $(this).hasClass('numeric');
var alpha = $(this).hasClass('alpha');
if (required && value.length===0) {
displayError(this,'required');
pass=false;
}
else if (email && valueExists && !tests.email.test(value)) {
displayError(this,'email');
pass=false;
}
else if (numeric && valueExists && !tests.numeric.test(value)) {
displayError(this,'numeric');
pass=false;
}
else if (alpha && valueExists && !tests.alpha.test(value)) {
displayError(this,'alpha');
pass=false;
}
});
return pass;
});
});
/*]]>*/
</script>
As well as the sendform.php which is called when submitting the form:
<?php
ini_set("display_errors", "0");
$post_data = filter_input_array( INPUT_POST );
$name = $post_data["name"];
$email = $post_data["email"];
$phone = $post_data["phone"];
$website = $post_data["website"];
$message = $post_data["message"];
# select data that needs validation
$validate = array(
'required' => array($name,$email,$message),
'validEmail' => array($email),
'validNumber' => array($phone),
'validAlpha' => array($name)
);
$formcontent = "Name: $name \nE-Mail: $email \nPhone: $phone \nWebsite: $website \nMessage: $message \n";
//*$formcontent = wordwrap($formcontent, 70, "\n", true);
$recipient = "mail@test.com";
$subject = "Testmail";
/*$mailheader = "From: $email \r\n";**/
$mailheader .= "Reply-To: $name <$email>\r\n";
$mailheader .= "Return-Path: $name <$email>\r\n";
$mailheader .= "Content-Type: text/plain\r\n";
$mailheader .= "Organization: Sender Organization\r\n";
$mailheader .= "MIME-Version: 1.0\r\n";
$mailheader .= "Content-type: text/plain; charset=UTF-8\r\n";
$mailheader .= "X-Priority: 3\r\n";
$mailheader .= "X-Mailer: PHP". phpversion() ."\r\n";
$mailheader .= "From: $name <$email>\r\n";
function sendMail() {
global $formcontent, $recipient, $subject, $mailheader;
mail($recipient, $subject, $formcontent, $mailheader);
}
# error messages
$errorsMsgs = array(
'required' => 'Please fill out all required fields.',
'validEmail' => 'is an invalid email address.',
'validNumber' => 'is an invalid number.',
'validAlpha' => 'contains invalid characters. This field only accepts letters and spaces.'
);
$errorMarkup = "<h1>We found a few errors :-(</h1><h2>Please fix these errors and try again</h2><ol>";
$errorMarkupEnd = "</ol>";
$successMarkup = "<h1>Success!</h1><h2>Your form was sent successfully.</h2>";
$backMarkup = "<a href=\"" . $_SERVER['HTTP_REFERER'] . "\">Back to form</a>";
# begin state
$valid = true;
# loop through fields of error types
foreach ($validate as $type => $fields) {
# loop through values of fields to be tested
foreach ($fields as $value) {
# throw error if value is required and not entered
if ($type === 'required' && strlen($value) === 0) {
$errorMarkup .= "<li>$errorsMsgs[$type]</li>";
$valid = false;
break;
}
else if (
$type === 'validEmail' && !filter_var($value, FILTER_VALIDATE_EMAIL) ||
$type === 'validNumber' && !preg_match('/^[0-9 ]+$/', $value) ||
$type === 'validAlpha' && !preg_match('/^[a-zA-Z ]+$/', $value)
) {
if (strlen($value) === 0) {break;} # skip check if value is not entered
$errorMarkup .= "<li>\"$value\" $errorsMsgs[$type]</li>";
$valid = false;
continue;
}
}
}
function isUTF8($string){
return (utf8_encode(utf8_decode($string)) == $string);
}
if ($valid) {
//*isUTF8($subject);
//*isUTF8($formcontent);
sendMail();
$body = $successMarkup . $backMarkup;
$title = "Form sent";
} else {
$body = $errorMarkup . $errorMarkupEnd . $backMarkup;
$title = "Form errors";
}
There are two problems I am struggling with at that point:
-
If you enter invalid characters into the form it will not only return an error for the field with the invalid value, but for all of them.
-
The popup which tells you that the form was successfully send appears whether or not the form was actually send – so I obviously need to put it behind the validation.
In your contact.php form you will first have the form type which could be similar to this
this tells your contact form where to get the post.php form, as mine is in the same folder it only needs the name, you set the name of your form which for me is contactUs, this will be explained in a minute, then you have onsubmit, this is the submit button at the bottom of your contact form, so when somebody clicks on submit it returns the validateForm() which is this.
this goes under your form so that it is easier for it to find the script, i will use this as an example to hopefully teach you what you need to know to understand
here is the function for it
in your if statement you type the name of your form which for me is contactUs, the name of the value for my contact form is name, so this will check to see if a name is valid.
in my function it checks to see if its null(empty), or “”, which is the same as empty, if it is empty
give them alerttxt, which is defined in my validate_required as “Valid email must be supplied”, this is set in the function validate_required(field, alerttxt), field is the name of my form and the name of the field i want verified and alerttxt is that shown above, if it is empty then it returns false, if it is not then it is true.
the if statement is
you have got the results back from your form, and
if false == validate_required, if thevalidate_requiredis false as well then they are equal and the alert message is given instead, ifvalidate_requiredis true then they do not match and the statement is not false therefore not needing validated, hope this helps, read through the javascript and you will get what it means