Monday, February 19, 2018

How to add form validation with Contact Form 7 (or other form types)

Step 1: Create form and fields

Please make sure to add a "name" value to each field, this is so it can be read by the validation plugin.
[text* first_name id:first_name name:first_name minlength:2 placeholder "First name"]
Edit

Step 2: Add js dependencies to the theme

Files that need to be added are: jquery.validate.js and additional-methods.js
Edit

Step 3: Add js calls in your custom js file

See comments for additional info
   // Validate form on Page 1
   // #wpcf7-f1356-p1892-o1 is the id of the form
  $("#wpcf7-f1356-p1892-o1 .wpcf7-form").validate({

    // Specify the validation rules. It uses the "name" values for each field.  See http://jqueryvalidation.org/validate/.
    rules: {
      first_name: {
        required: true,
        minlength: 2,
      },
      last_name: {
        required: true,
        minlength: 2
      },
      email: {
        required: true,
        email: true
      },
      telephone: {
        required: true,
        minlength: 2
      },
      company: {
        required: true,
        minlength:2
      }
    },

    // Specify the validation error messages. It uses the "name" values for each field.
    messages: {
      first_name: {
        required: "Please provide your first name",
        minlength: "First name must be longer than 1 character." 
      },
      last_name: {
        required: "Please provide your last name",
        minlength: "Last name must be longer than 1 character." 
      },
      email: {
        required: "Please provide your email address",
        email: "This email address doesn't look right" 
      },
      telephone: {
        required: "Please provide your phone number",
        minlength: "Company name must be longer than 1 character." 
      },
      company: {
        required: "Please provide your company name",
        minlength: "This looks like it is an invalid phone number" 
      }

    }

  });
Edit

Step 4: Add styles to the form

That's it :)

No comments:

Post a Comment