Question

I am trying to do some form validation on a very simple form. I will have a Name field, an Email field and a Message field.

Basically I want to validate the name to check if there are more than 1 characters, I want to validate email against a valid email format and I want to validate the message to check for more than 1 character.

I also want the error class to be applied to the field immediately after focusing on the next field instead of on submit, but I can't seem to get it to work and my error/success classes are not being applied either. Could anyone take a look and let me know what I've got wrong?

HTML:

<form id="contactform" name="contact" action="{{ contents.form_submissions.api.create }}" method="post">
 <p>
  <label for="name">Name:</label>
  <input type="text" id=name name="content[name]" placeholder="Name" required tabindex="1" />
 </p>
 <p>
  <label for="email">Email:</label>
  <input type="text" id=email name="content[email]" placeholder="example@domain.com" required tabindex="2" />
 </p>
 <p>
  <label for="message">Message:</label>
  <textarea name="content[message]" id="message" tabindex="3" required></textarea>
 </p>
 <p class="action">
  <input name="submit" type="submit" id="submit" tabindex="4" value="Send Message" />
 </p>
</form>

Javascript:

$(document).ready(function() {
    var validator = $("#contactform").validate({
        errorClass: 'input-error',
        validClass: 'input-valid',
        rules: {
            name: "required",
            email: "required",
            message: {
                required: true,
                minlength: 1
            }
        },
        messages: {
            name: "Enter your name",
            email: "Enter your email",
            message: {
                required: "Enter a message",
                minlength: 1
            }
        }
    });
});

Here's a JSFiddle

Was it helpful?

Solution

  1. Your name attributes have to match the rule names (i.e. if you have name="content[name]", your rule must be 'content[name]': "required"

  2. Don't use required attributes in your input elements unless you want HTML5 Validation and not jQuery Validation.

  3. Call $('#contactform').valid() to trigger validation at any time

Working example: http://jsfiddle.net/ryleyb/kv8T8/8/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top