PHP Form - Empty input enter this text - Validation
- by James Skelton
No doubt very simple question for someone with php knowledge.
I have a form with a datepicker, all is fine when a user has selected a date the email is send with:
Date: 2012 04 10
But i would like if the user has skipped this and left blank (as i have not made this required) to send as:
Date: Not Entered (<-- Or something)
Instead at the minute of course it reads:
Date:
Form input
<input type="text" class="form-control" id="datepicker" name="datepicker" size="50" value="Date Of Wedding" />
This is the validator
$(document).ready(function(){
//validation contact form
$('#submit').click(function(event){
event.preventDefault();
var fname = $('#name').val();
var validInput = new RegExp(/^[a-zA-Z0-9\s]+$/);
var email = $('#email').val();
var validEmail = new RegExp(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
var message = $('#message').val();
if(fname==''){ showError('<div class="alert alert-danger">Please enter your name.</div>', $('#name')); $('#name').addClass('required'); return;}
if(!validInput.test(fname)){ showError('<div class="alert alert-danger">Please enter a valid name.</div>', $('#name')); $('#name').addClass('required'); return;}
if(email==''){ showError('<div class="alert alert-danger">Please enter an email address.</div>', $('#email')); $('#email').addClass('required'); return;}
if(!validEmail.test(email)){ showError('<div class="alert alert-danger">Please enter a valid email.</div>', $('#email')); $('#email').addClass('required'); return;}
if(message==''){ showError('<div class="alert alert-danger">Please enter a message.</div>', $('#message')); $('#message').addClass('required'); return;}
// setup some local variables
var request;
var form = $(this).closest('form');
// serialize the data in the form
var serializedData = form.serialize();
// fire off the request to /contact.php
request = $.ajax({
url: "contact.php",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
$('.contactWrap').show( 'slow' ).fadeIn("slow").html(' <div class="alert alert-success centered"><h3>Thank you! Your message has been sent.</h3></div> ');
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error( "The following error occured: "+ textStatus, errorThrown );
});
});
//remove 'required' class and hide error
$('input, textarea').keyup( function(event){
if($(this).hasClass('required')){
$(this).removeClass('required');
$('.error').hide("slow").fadeOut("slow");
}
});
// show error
showError = function (error, target){
$('.error').removeClass('hidden').show("slow").fadeIn("slow").html(error);
$('.error').data('target', target);
$(target).focus();
console.log(target);
console.log(error);
return;
}
});