Thank you! Your feedback has been delivered
Thank you! Your feedback has been sent

Form validation - Valid phone, email & minimum time functions

Not sure if anyone here can help with this but I'm currently using a form validation script that detects required empty form fields and would like to add code to ensure only numbers are inserted into the 'Phone' field, and that a valid email address is only inserted into the 'Email' field (that the input data must contain at least an @ sign and a dot (.). Also, the @ must not be the first character of the email address, and the last dot must at least be one character after the @ sign).

Also if possible I would like to include code that can set a minimum time between page-load and form-submit... like 5 seconds?

If any errors are detected I would like the user prompted to complete as per the existing script.

The following is the script I'm using:

  <script type="text/javascript" language="JavaScript">

  var FormName = "theForm";

  var RequiredFields = "Name,Email,Phone";


  function ValidateRequiredFields()
  var FieldList = RequiredFields.split(",")
  var BadList = new Array();
  for(var i = 0; i < FieldList.length; i++) {
      var s = eval('document.' + FormName + '.' + FieldList[i] + '.value');
      s = StripSpacesFromEnds(s);
      if(s.length < 1) { BadList.push(FieldList[i]); }
  if(BadList.length < 1) { return true; }
  var ess = new String();
  if(BadList.length > 1) { ess = 's'; }
  var message = new String('nnThe following field' + ess + ' are required:n');
  for(var i = 0; i < BadList.length; i++) { message += 'n' + BadList[i]; }
  return false;

  function StripSpacesFromEnds(s)
  while((s.indexOf(' ',0) == 0) && (s.length> 1)) {
      s = s.substring(1,s.length);
  while((s.lastIndexOf(' ') == (s.length - 1)) && (s.length> 1)) {
      s = s.substring(0,(s.length - 1));
  if((s.indexOf(' ',0) == 0) && (s.length == 1)) { s = ''; }
  return s;
  // -->


The following is the form html:

                <form action="contactengine_required_programs.php" method="post" id="theForm" name="theForm" onsubmit="return ValidateRequiredFields();">
                <div class="control-group">
                <label class="control-label" for="Name">*NAME</label>
                <div class="controls">
                <input type="text" class="span4" id="Name" name="Name" placeholder="Name"/>

                <div class="control-group">
                <label class="control-label" for="Email">*EMAIL</label>
                <div class="controls">
                <input type="text" class="span4" name="Email" id="Email" placeholder="Email"/>

                <div class="control-group">
                <label class="control-label" for="Phone">*PHONE</label>
                <div class="controls">
                <input type="text" class="span4" id="Phone" name="Phone" placeholder="Phone"/>
                <div class="control-group">                            
                <button type="submit" class="btn">Send Message</button>                            


And for reference this is the PHP used to process the form:


$EmailFrom = "xxx";
$EmailTo = "xxx";
$Subject = "Query from xxx";
$Name = Trim(stripslashes($_POST['Name'])); 
$Phone = Trim(stripslashes($_POST['Phone'])); 
$Email = Trim(stripslashes($_POST['Email'])); 

// validation
if (!$validationOK) {
  print "<meta http-equiv="refresh" content="0;URL=error.html">";

// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "n";
$Body .= "Phone: ";
$Body .= $Phone;
$Body .= "n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "n";

// send email 
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");

// redirect to success page 
if ($success){

  print "<meta http-equiv="refresh" content="0;URL=contact_sent.html">";

  print "<meta http-equiv="refresh" content="0;URL=URL=error.html">";

If anyone can advise the amendments to add the functions I require that would be great!

User Gravatar


Posted Jan 13 2014 15:34 UTC


  • Assigned To elado
  • Solved
  • javascript

4 Replies

The right way to do it is to use jQuery and a form validation library: or

It's pretty easy to setup.

Let me be straight here: the code you're using is not well-written; it looks archaic, uses functions like eval, strips spaces with too much code, and uses wrong conventions.

Also, the user experience it produces is bad, as it's uses alert instead of pointing the right input.

Use the easy-to-use libraries above, supply nicer user experience, and easier way to integrate the validations (with minimum JavaScript).

As for allowing to send the form only 5 seconds after page load: is this to prevent spam? because it won't help.

I see you don't use jQuery, and you'll have to use JS with the longer way:

Add id to your button:

<button type="submit" class="btn" id="formSubmitButton" disabled>Send Message</button>

add to JS:

var formSubmitButton = document.getElementById('formSubmitButton');
setTimeout(function () {
  formSubmitButton.disabled = false;
}, 5000);

But ask yourself first what you want to achieve with it.

User Gravatar


Posted Jan 13 2014 18:27 UTC


This didn't solve your task? Get your own custom solution.

Thanks for the advice. I will look into your recommended jQuery form validation libraries. As for the delay with the form submission, it is one of a number of features I'm trying to use to minimise spam without resorting to CAPTCHA.

User Gravatar


Posted Jan 13 2014 21:28 UTC

It won't help you much, as spammers don't execute JavaScript.

You can use a technique called honeypot captcha:

User Gravatar


Posted Jan 13 2014 22:28 UTC

Hey, You should use regular expressions in order to obtain the desired result.

var check_name = /^[A-Za-z0-9 ]{3,20}$/;
var check_email = /^([w-]+(?:.[w-]+)*)@((?:[w-]+.)*w[w-]{0,66}).([a-z]{2,6}(?:.[a-z]{2})?)$/i;
var phone_number = /^d+$/;

function ValidateRequiredFields (form) {
    var name = form.Name.value;
    var number = form.Phone.value;
    var email = form.Email.value;
    var errors = [];

    if(!check_name.test(name)) {
        errors[errors.length] = "You must enter a valid Name.";

    if(!phone_number.test(number)) {
        errors[errors.length] = "You must enter a valid Phone Number.";

    if(!check_email.test(email)) {
        errors[errors.length] = "You must enter a valid Email Address.";

    if(errors.length > 0) {
        return false;

    return true;

function reportErrors(errors) {
   var msg = "Please Enter Valide Data...n";
   for (var i = 0; i < errors.length; i++) {
      var numError = i + 1;
      msg += "n" + numError + ". " + errors[i];

The html remains as it is only change is in form onSubmit method;

<form action="contactengine_required_programs.php" method="post" id="theForm" name="theForm" onsubmit="return ValidateRequiredFields(this);">
User Gravatar


Posted Jan 14 2014 0:39 UTC

Add a reply

By posting a reply on CodersClan you agree to our Terms & Conditions