How to validate a form with Javascript and jQuery?

When we have a form that must be completed by the user it is necessary to guarantee that the information that the user captures is clean, correct and useful. The typical fields that we must validate are:


  • An email validation
  • Required field validation
  • Date validation
  • Website URL validation
  • File upload validation
  • Dropdown validation

Example:

The following example validates a form using JavaScript and jQuery, I will show you how to create the validations in javascript and jQuery sending a error messages. Find the source code below:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Form validation in javascript with example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" type="text/css" href="css/style.css">
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">


    <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script type="text/javascript" src="js/jquery.validate.min.js"></script>
    <script type="text/javascript" src="js/additional-methods.min.js"></script>

    <script type="text/javascript">
        jQuery(document).ready(function ($) {
            $("#smart-form").validate({
                errorClass: "state-error",
                validClass: "state-success",
                errorElement: "em",
                highlight: function (element, errorClass, validClass) {
                    $(element).closest('.field').addClass(errorClass).removeClass(validClass);
                },
                unhighlight: function (element, errorClass, validClass) {
                    $(element).closest('.field').removeClass(errorClass).addClass(validClass);
                },
                errorPlacement: function (error, element) {
                    if (element.is(":radio") || element.is(":checkbox")) {
                        element.closest('.option-group').after(error);
                    } else {
                        error.insertAfter(element.parent());
                    }
                }
            });
        });
    </script>

</head>

<body class="woodbg">

    <div class="smart-wrap">
        <div class="smart-forms smart-container wrap-2">

            <div class="form-header header-primary">
                <h4><i class="fa fa-pencil-square"></i>Validar Form con JavaScript y jQuery</h4>
            </div><!-- end .form-header section -->

            <form method="post" id="smart-form">
                <div class="form-body">

                    <div class="frm-row">
                        <div class="section colm colm6">
                            <label for="firstname" class="field prepend-icon">
                                <input type="text" name="firstname" id="firstname" class="gui-input"
                                       data-rule-required="true"
                                       data-rule-letterswithbasicpunc="true"
                                       data-msg-required="First name is required"
                                       data-msg-letterswithbasicpunc="Please enter letters only"
                                       placeholder="Nombres...">
                                <span class="field-icon"><i class="fa fa-user"></i></span>
                            </label>
                        </div><!-- end section -->

                        <div class="section colm colm6">
                            <label for="lastname" class="field prepend-icon">
                                <input type="text" name="lastname" id="lastname" class="gui-input"
                                       data-rule-required="true"
                                       data-rule-letterswithbasicpunc="true"
                                       data-msg-required="Last name is required"
                                       data-msg-letterswithbasicpunc="Please enter letters only"
                                       placeholder="Apellidos...">
                                <span class="field-icon"><i class="fa fa-user"></i></span>
                            </label>
                        </div><!-- end section -->
                    </div><!-- end .frm-row section -->

                    <div class="section">
                        <label for="useremail" class="field prepend-icon">
                            <input type="email" name="useremail" id="useremail" class="gui-input"
                                   data-rule-required="true"
                                   data-rule-email="true"
                                   data-msg-required="Enter email address"
                                   data-msg-email="Enter a VALID email address"
                                   placeholder="Nombre de usuario">
                            <span class="field-icon"><i class="fa fa-envelope"></i></span>
                        </label>
                    </div><!-- end section -->

                    <div class="section">
                        <label for="website" class="field prepend-icon">
                            <input type="url" name="website" id="website" class="gui-input"
                                   data-rule-required="true"
                                   data-msg-required="Enter website url"
                                   data-rule-url="true"
                                   data-msg-url="Enter VALID url"
                                   placeholder="Web site">
                            <span class="field-icon"><i class="fa fa-globe"></i></span>
                        </label>
                    </div><!-- end section -->

                    <div class="section">
                        <label class="field select">
                            <select id="language" name="language"
                                    data-rule-required="true"
                                    data-msg-required="Select a language">
                                <option value="">Lenguaje...</option>
                                <option value="EN">English</option>
                                <option value="FR">French</option>
                                <option value="SP">Spanish</option>
                                <option value="CH">Chinese</option>
                                <option value="JP">Japanese</option>
                            </select>
                            <i class="arrow double"></i>
                        </label>
                    </div><!-- end section -->

                    <div class="section">
                        <label for="file1" class="field file">
                            <span class="button btn-primary"> Choose File </span>
                            <input type="file" class="gui-file" name="upload1" id="file1" onChange="document.getElementById('uploader1').value = this.value;"
                                   data-rule-required="true"
                                   data-msg-required="Please upload a file"
                                   data-rule-accept="image/jpeg,image/pjpeg,image/png,image/gif,image/bmp,image/tiff"
                                   data-msg-accept="Only image files allowed"
                                   data-rule-filesize="10485760"
                                   data-msg-filesize="Please upload 10MB or less">
                            <input type="text" class="gui-input" id="uploader1" placeholder="Seleccionar archivo" readonly>
                        </label>
                    </div><!-- end  section -->

                    <div class="section">
                        <label class="field select-multiple">
                            <select name="mobileos" id="mobileos"
                                    data-rule-required="true"
                                    data-msg-required="Select an OS" multiple>
                                <option value="0">Windows 10 </option>
                                <option value="1">Windows 7 </option>
                                <option value="2">Google Android</option>
                                <option value="3">Apple iOS</option>                                
                            </select>
                        </label>
                    </div><!-- end  section -->

                    <div class="section">
                        <label for="comment" class="field prepend-icon">
                            <textarea class="gui-textarea" id="comment" name="comment"
                                      data-rule-required="true"
                                      data-msg-required="Please enter your comments"
                                      placeholder="Comentario">
                            </textarea>
                            <span class="field-icon"><i class="fa fa-comments"></i></span>
                            <span class="input-hint">
                                <strong>DO NOT:</strong> Be negative or off topic, we expect a great comment...
                            </span>
                        </label>
                    </div><!-- end section -->

                </div><!-- end .form-body section -->
                <div class="form-footer">
                    <button type="submit" class="button btn-primary"> Validate Form </button>
                    <button type="reset" class="button"> Cancel </button>
                </div><!-- end .form-footer section -->
            </form>

        </div><!-- end .smart-forms section -->
    </div><!-- end .smart-wrap section -->

    <div></div><!-- end section -->

</body>
</html>

What did you think of the example?
I hope you liked and served this article based on how to validate a form in JavaScript and jQuery with error messages. I would like to receive your comments and suggestions. Your comments are very valuable to improve every day, questions or comments about this article are always welcome.

Download example

Artículos relacionados
0 Comentarios
Enviame un comentario