» » » How to validate a form with jQuery validation plugin

How to validate a form with jQuery validation plugin

posted in: Ajax, Javascript, WordPress

When you want to do the form validation you can do from the client-side and server-side. I like to do on the client-side so users can get the notification message right away after leaving the input field. The form validation on the client site is very useful when your form contains a lot of fields. On jquery plugin that I often use, it is jquery validation. It is easy to use and I can add my custom method, custom message, and custom rules.

After you download the plugin and install it in your site by following the document, you can initiate the plugin and it will be ready for use.

Here is an example

HTML file:

<form class="cmxform" id="commentForm" method="get" action="">
  <fieldset>
    <legend>Please provide your name, email address (won't be published) and a comment</legend>
    <p>
      <label for="cname">Name (required, at least 2 characters)</label>
      <input id="cname" name="name" minlength="2" type="text" required>
    </p>
    <p>
      <label for="cemail">E-Mail (required)</label>
      <input id="cemail" type="email" name="email" required>
    </p>
    <p>
      <label for="curl">URL (optional)</label>
      <input id="curl" type="url" name="url">
    </p>
    <p>
      <label for="ccomment">Your comment (required)</label>
      <textarea id="ccomment" name="comment" required></textarea>
    </p>
    <p>
      <input class="submit" type="submit" value="Submit">
    </p>
  </fieldset>
</form>
<!-- show message here -->
<div id="message"></div>

Initiate the plugin in the script:

$("#commentForm").validate();

You can look at the demo from here.

Set the rule, custom message and submit handler:

The sample above we add the “required” keyword at the HTML for the required field but you can add the required field at the rules in the options too. I prefer options. Below is an example of using the options.

$("#commentForm").validate({  
    rules: {
        cname: {
            required: true
        },
        cemail: {
            required: true,
        }
    },
    messages: {
        cname: "error.",
        cemail: "error."
    },
    submitHandler: function (form, e) {
        e.preventDefault();
        $.post('update_profile.php', $(form).serialize(), function(data) {
            $("#message").html(data);
            $("#message").fadeIn(500);
            $("#message").fadeOut(500);
        });
    }
});

The plugin provides more methods and adds on that you can use. Read more at the documentation.

Input file validation with custom rule method:

In my last work, I have to set the upload file fields with mandatory, restrict the file extension and file size. I have to do the validation on the client-side. So I chose the jQuery validation plugin and I have to create the custom rule method for the file size limitation. I will share it with you here.

In PHP code

<?php
<form id="apply-form-5" enctype="multipart/form-data" method="post">
    <input type="hidden" name="action" value="save_jobapp_logs">
    
    <section class="page-content margin-b-100 apply-job-form">
        <div class="container">
            <div class="row">
                <div class="col-md-8 col-lg-6">

                    <!-- progress bar -->
                    <div class="progress">
                      <div class="progress-bar progress-bar-striped active" role="progressbar"
                      aria-valuenow="95" aria-valuemin="0" aria-valuemax="95" style="width:95%">
                        95% complete
                      </div>
                    </div>


                    <h3><?php _e('Supporting Documentation', 'apple'); ?></h3>                    
                    <div class="form-group">
                        <label for="exampleInputFile" style="margin-top: 10px;"><?php _e('Please upload your Passport', 'apple'); ?> <br>(<?php printf(__('Acceptable extensions %s', 'apple'), ".pdf .doc .docx .jpg and .jpeg"); ?>)</label>
                        <div class="form-group">
                            <input type="file" accept=".pdf,.doc,.docx,.jpg,.jpeg" name="attached_passport" id="attached_passport">
                        </div>
                    </div>

                    <button id="btnSubmitForm-5" type="button" class="btn btn-primary margin-t-25"><?php _e('Finish', 'apple'); ?></button>
                </div>
            </div>
        </div>

        <!-- modal  -->
        <div id="modal-form-5" class="modal fade" tabindex="-1" role="dialog" style="top: 25%;">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header bg-primary">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                        <h4 class="modal-title"><?php _e('Job application', 'apple'); ?></h4>
                    </div>
                    <div class="modal-body">
                        <p class="text-result"><?php _e('Your application has been saved.', 'apple'); ?></p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal"><?php _e('Close', 'apple'); ?></button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->
    </section><!-- / section ends -->  
</form>
?>

In js code

$(document).ready(function () {
    
    var $frmNextStep5 = $("#btnSubmitForm-5");
    var $frmStep5 = $("#apply-form-5");

    /**
     * set the status value which button is clicked and submit the form
     */        
    $frmNextStep5.on("click", function () {
        $frmNextStep5.attr('data-isclick','1'); 
        $frmStep5.submit(); // validate before sending to ajax
    });        

    /**
     * form validattion
     * @link https://jqueryvalidation.org/validate/
     */
    $frmStep5.validate({          
        rules: {
            attached_passport: {
                required: true,
                extension: "docx|doc|pdf|jpg|jpeg", // work with additional-mothods.js
                filesize: 2000000, // 2MB,  this filesize method is the custom method that I create. the code can be found in this post.
            }
        },
        highlight: function (element) {          
            $(element).closest('.form-group').addClass('has-error');
        },
        unhighlight: function (element) {
            $(element).closest('.form-group').removeClass('has-error');
        },
        errorElement: 'span',
        errorClass: 'help-block',
        errorPlacement: function (error, element) {
            if (element.parent('.input-group').length) {
                error.insertAfter(element.parent());
            } else {
                error.insertAfter(element);
            }
        },
        messages: {
            attached_passport:{              
                filesize:"File size must be less than 2 mb."
            }
        }                     
    });


    /**
     * save data into the db via ajax
     * I use ajaxForm plugin for sending the form data via ajax
     * We can use the ajax functions as normal such as beforeSubmit()
     *
     * @link https://github.com/jquery-form/form
     * @link http://malsup.com/jquery/form/
     */
    $frmStep5.ajaxForm({
        url: "<?php echo admin_url('admin-ajax.php') ?>",  // WP already has the ajax file, we just call it from admin.
        method: 'post',
        dataType: 'json',  // dataType should be json
        data: { 
            'step' : '5'
        },  // pass the object value you want to action function(PHP), the form data automatic sends by ajaxForm plugin. So we don't need to pass the form data here.
        beforeSubmit: function () {
            // console.log("beforeSubmit");             
        },
        beforeSend: function () {    
            // # disable the button to prevent the users click twice while is processing
            $frmNextStep5.prop('disabled', true);    
        },
        success: function (data) {
            // console.log(data);

            if(data.result === 'true') { // data object is sent from the form action, in this case, it is "save_jobapp_logs" which is a PHP function.
                // # show the message on the Bootstrap modal
                $('#modal-form-5').on('hidden.bs.modal', function (e) {
                    // after close the modal, what you want to do next....                                             
                })                
                
                // open the modal
                $('#modal-form-5').modal();

            }else{
                alert(data.msg);                  
            }

            
        },
        error: function (jqXHR, exception) {
            // just show the error that causes the ajax fail
            var msg = '';
            if (jqXHR.status === 0) {
                msg = 'Not connect.\n Verify Network.';
            } else if (jqXHR.status == 404) {
                msg = 'Requested page not found. [404]';
            } else if (jqXHR.status == 500) {
                msg = 'Internal Server Error [500].';
            } else if (exception === 'parsererror') {
                msg = 'Requested JSON parse failed.';
            } else if (exception === 'timeout') {
                msg = 'Time out error.';
            } else if (exception === 'abort') {
                msg = 'Ajax request aborted.';
            } else {
                msg = 'Uncaught Error.\n' + jqXHR.responseText;
            }
            console.log(msg);

            // # enable the button to prevent the users click twice while is processing
            $frmNextStep5.prop('disabled', false);
        },    
        complete: function (xhr) {

        }
    });

});

The custom rule for file size limitation. I create in the external file and include it in the functions.php or custom plugin. You can choose where you want to include this js file.

/**
 * Filesize validation extension
 * 
 * dependency: jquery.validation plugin
 * @link https://stackoverflow.com/questions/33096591/validate-file-extension-and-size-before-submitting-form
 * @link https://github.com/jquery-validation/jquery-validation/releases/tag/1.13.1
 */
$.validator.addMethod('filesize', function (value, element, param) {
  return this.optional(element) || (element.files[0].size <= param)
}, 'File size must be less than {0} bytes.');

The file extension restriction, you must include the additional-methods.js that comes with the download bundle of jQuery validation plugin. The last version of the plugin can be found here. The additional-methods.js must be the same version of jquery-validate.js. The jquery-validate.js is the dependency of additional-methods.js.