Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a simple contact form that posts to MySql on submit, I am trying to validate on the client side before submitting the form (I will implement server side validation after I get the client side to work). For some reason when I submit the form it posts to the DB but doesn't fire up the client side validation. Any help would be appreciated.

This is the HTML (twitter bootstrap) code:

<form action="/contact.php" method="post" id="contactUs">
    <div class="control-group">
       <label class="control-label" for="Name">NAME<sup>*</sup></label>
       <div class="controls">
         <input type="text" class="span4" name="name" placeholder="Name" id="name">
         <span class="help-block"></span> 
        </div>
    </div>
    <div class="control-group">
       <label class="control-label" for="Email">EMAIL<sup>*</sup></label>
       <div class="controls">
         <input type="text" class="span4" name="email" placeholder="Email" id="email">
         <span class="help-block"></span> 
       </div>
    </div>
    <div class="control-group">
       <label class="control-label" for="Subject">Subject<sup>*</sup></label>
       <div class="controls">
         <input type="text" class="span4" name="subject" placeholder="Subject" id="subject">
         <span class="help-block"></span>
       </div>
     </div>
     <div class="control-group">
        <label for="textarea" class="control-label" for="Comment">COMMENTS<sup>*</sup></label>
        <div class="controls">
          <textarea rows="5" class="span6" name="comments" id="message"></textarea>
          <span class="help-block"></span>
        </div>
      </div>
      <div class="control-group form-button-offset">
      <input type="submit" class="btn btn-large btn-primary pull-right" value="Send Message" />
     </div>
      <input type="hidden" name="redirect" value="contact_us.html" />

<script src="js/jquery-1.9.0.min.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script src="js/contactUs.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/bootstrap.min.js"></script>

Below is the code for the contactUs.js:

$(document).ready(function(){
$('#contactUs').validate({
    rules: {
        name: {
            minlength: 4,
            required: true
        },
        email: {
            required: true,
            email: true,
        },
        subject: {
            minlength: 5,
            required: true
        },
        submission_Reason: {
            minlength: 5,
            required: true
        },
        comments: {
            minlength: 8,
            required: true,
        }
    },
    messages: {
        name: "Please enter your first and last name",
        email: "Please enter a valid email address",
        subject: "Please enter a subject",
        comments: "Please enter a short message",
    },
    highlight: function (element, errorClass, validClass) {
        $(element).closest('.control-group').removeClass('success').addClass('error');
    },
    unhighlight: function (element, errorClass, validClass) {
        $(element).closest('.control-group').removeClass('error').addClass('success');
    },
    success: function (label) {
        $(label).closest('form').find('.valid').removeClass("invalid");
    },
    errorPlacement: function (error, element) {
        element.closest('.control-group').find('.help-block').html(error.text());
    }
});
};

and the PHP contact.php file:

    <?php

$con=mysqli_connect("host","username","password","dbname");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="INSERT INTO contactUs (name, email, subject, comments)
VALUES
('$_POST[name]','$_POST[email]','$_POST[subject]','$_POST[comments]')";

$sql="INSERT INTO contactUs (`date_created`) VALUES (now())";

if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }
echo "Your form has been received, Thank you!";

mysqli_close($con);

?>

When I submit the form the client side validation is not triggered and the result is:

  • the form gets submitted and posts to DB
  • I get: Your form has been received, Thank you!

What am I doing wrong? why isn't the validation happening?

share|improve this question
Have you checked your browser's console for any errors (Press Ctrl+Shift+J to open the console) – koala_dev 2 days ago
WOW! koala thank you I did it before but didn't pay too much attention to what came up. I did it again now and paid more attention. It was a stupid ")" missing. – user2715832 yesterday

1 Answer

try this

$.validator.setDefaults(
{
    submitHandler: function() { submit(); },
    showErrors: function(map, list) 
    {
        this.currentElements.parents('label:first, .controls:first').find('.error').remove();
        this.currentElements.parents('.control-group:first').removeClass('error');

        $.each(list, function(index, error) 
        {
            var ee = $(error.element);
            var eep = ee.parents('label:first').length ? ee.parents('label:first') : ee.parents('.controls:first');

            ee.parents('.control-group:first').addClass('error');
            eep.find('.error').remove();
            eep.append('<p class="error help-block"><span class="label label-important">' + error.message + '</span></p>');
        });
        //refreshScrollers();
    }
});

$.validator.setDefaults(
{
    submitHandler: function() { submit(); },
    showErrors: function(map, list) 
    {
        this.currentElements.parents('label:first, .controls:first').find('.error').remove();
        this.currentElements.parents('.control-group:first').removeClass('error');

        $.each(list, function(index, error) 
        {
            var ee = $(error.element);
            var eep = ee.parents('label:first').length ? ee.parents('label:first') : ee.parents('.controls:first');

            ee.parents('.control-group:first').addClass('error');
            eep.find('.error').remove();
            eep.append('<p class="error help-block"><span class="label label-important">' + error.message + '</span></p>');
        });
        //refreshScrollers();
    }
});

$(function()
{
    // validate signup form on keyup and submit
    $("#validateSubmitForm").validate({
        rules: {
        name: {
            minlength: 4,
            required: true
        },
        email: {
            required: true,
            email: true,
        },
        subject: {
            minlength: 5,
            required: true
        },
        submission_Reason: {
            minlength: 5,
            required: true
        },
        comments: {
            minlength: 8,
            required: true,
        }
        },
        messages: {
        name: "Please enter your first and last name",
        email: "Please enter a valid email address",
        subject: "Please enter a subject",
        comments: "Please enter a short message"
    });

    // propose username by combining first- and lastname
    $("#username").focus(function() {
        var firstname = $("#firstname").val();
        var lastname = $("#lastname").val();
        if(firstname && lastname && !this.value) {
            this.value = firstname + "." + lastname;
        }
    });

    //code to hide topic selection, disable for demo
    var newsletter = $("#newsletter");
    // newsletter topics are optional, hide at first
    var inital = newsletter.is(":checked");
    var topics = $("#newsletter_topics")[inital ? "removeClass" : "addClass"]("gray");
    var topicInputs = topics.find("input").attr("disabled", !inital);
    // show when newsletter is checked
    newsletter.click(function() {
        topics[this.checked ? "removeClass" : "addClass"]("gray");
        topicInputs.attr("disabled", !this.checked);
    });
});
share|improve this answer
Unfortunately it's not working. It's as if the page is ignoring the JS and goes straight to the <form action="/contact.php" method="post" id="contactUs"> – user2715832 2 days ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.