jQuery class based client-side validation

jQuery Validation using the class instead of the name value


Validate a form using the jquery validate plugin, but not able to use the ‘name’ value within the HTML. Instead of ‘name’ value use a class name so that you can write a validate rule one time and use it multiple times.

Here we go.. let’s write some code.

Markup

Wrap all form field inside ‘<div class=”validateContainer”> </div>’ and all inputs elements in ‘<div class=”validateField”> </div>’ which will help you to maintain your stucture and to write a common function for validate any form in your web-application.

<form>
    <div class="validateContainer">
        <div class="form-group">
            <div class="validateField">
                <input name="FirstName" type="text" id="FirstName" class="form-control validateRequired validateAlphaonly" placeholder="First Name *">
                <label>Enter your First Name</label>
            </div>
        </div>

        <div class="form-group">
            <div class="validateField">
                <input name="LastName" type="text" id="LastName" class="form-control validateRequired validateAlphaonly" placeholder="Last Name *">
                <label>Enter your Last Name</label>
            </div>
        </div>

        <div class="form-group">
            <div class="validateField">
                <input name="EmailId" type="text" id="EmailId" class="form-control validateRequired validateEmail" placeholder="Email Id *">
                <label>Enter your Email Id</label>
            </div>
        </div>

        <div class="form-group">
            <div class="validateField">
                <input name="MobileNo" type="text" maxlength="10" id="MobileNo" class="form-control validateRequired validateNumber validateMobileNoLimit" placeholder="Mobile No. *">
                <label>Enter your Mobile No.</label>
            </div>
        </div>

        <div class="row">
            <div class="col-md-6 col-sm-6 col-xs-12">
                <div class="form-group">
                    <div class="validateField">
                        <input name="City" type="text" id="City" class="form-control validateRequired validateAlphaonly" placeholder="City *">
                        <label>Enter City Name</label>
                    </div>
                </div>
            </div>
            <div class="col-md-6 col-sm-6 col-xs-12">
                <div class="form-group">
                    <div class="validateField">
                        <input name="Location" type="text" id="Location" class="form-control validateRequired validateAlphaonly" placeholder="Area *">
                        <label>Enter Area Name</label>
                    </div>
                </div>
            </div>
        </div>

        <div class="form-group">
            <div class="validateField">
                <input name="Password" type="password" maxlength="20" id="Password" class="form-control validateRequired validatePassword" placeholder="Password *">
                <label>Enter Password</label>
            </div>
        </div>

        <div class="form-group form-group1">
            <div class="validateField">
                <input name="PasswordConfirm" type="password" maxlength="20" id="PasswordConfirm" class="form-control validateRequired validateConfirmPassword" placeholder="Confirm Password *">
                <label>Enter Confirm Password</label>
            </div>
        </div>

        <div class="form-group checkbox">
            <label>
                <div class="validateField">
                    <input id="TermsConditions" type="checkbox" name="TermsConditions" class="form-control validateRequired" style="width: 13px;height: 13px;"> I accept <strong>terms &amp; conditions</strong>
                </div>
            </label>
        </div>

        <input type="submit" name="btnSubmit" value="Submit" id="btnSubmit" class="btn btn-default checkValidationBtn">
    </div>
</form>

Add some Style

You can change a style according to your theme.

form {
    background: #fff;
    padding: 30px;
    border-radius: 10px;
    margin: 30px 0px;
    box-shadow: 5px 5px 20px rgba(0, 0, 0, 0.08);
}
.form-group {
    margin-bottom: 25px;
}
.validateField {
    position: relative;
    width: 100%;
}
.validateField .form-control {
    position: relative;
    font-size: 18px;
    border: 0;
    box-shadow: none;
    border-bottom: 1px solid #ccc;
    border-radius: 0;
    padding: 8px 1px;
}
/* validation style */

.validateField.has-error .form-control {
    border-bottom: 1px solid #ff4e5a;
    box-shadow: none;
}
.validateField.has-success .form-control {
    border-bottom: 1px solid #17A007;
    box-shadow: none;
}
.validateField.has-error .help-block {
    color: #ff4e5a;
}
.validateField.has-success .help-block {
    color: #3AC729;
}
.validateField .help-block {
    position: absolute;
    background: #fff;
    font-family: 'Quicksand', sans-serif;
    font-weight: 100;
    font-size: 11px;
    width: 100%;
    bottom: -23px;
    height: 20px;
    z-index: 99;
    margin-bottom: 0;
    line-height: 1.42857143;
    text-align: left;
    line-height: 9px;
}
.validateField > label {
    margin-bottom: 0px;
    position: absolute;
    background: none;
    font-family: 'Quicksand', sans-serif;
    font-weight: 100;
    font-size: 11px;
    width: 100%;
    bottom: -23px;
    height: 20px;
    z-index: 99;
    margin-bottom: 0;
    line-height: 1.42857143;
    text-align: left;
    line-height: 9px;
    color: rgba(0, 0, 0, 0.45);
}

Event handling

Initialize validation

$('form').validate({
     ignore: [],
     onkeyup: function(element) {
         $(element).valid()
     },
     errorClass: 'help-block',
     errorElement: 'span',
     errorPlacement: function(error, e) {
         e.closest('.validateField').append(error);
         return false;
     },
     highlight: function(e) {
         console.log('validation error');
         $(e).closest('.validateField').removeClass('has-success has-error').addClass('has-error');
         $(e).closest('.help-block').remove();
         return false;
     },
     success: function(e) {
         console.log('validation success');
         // You can remove the .addClass('has-success') part if you don't want the inputs to get green after success!
         e.closest('.validateField').removeClass('has-success has-error').addClass('has-success');
         e.closest('.help-block').remove();
         return false;
     }
 });

Add class based validation rules using $.validator.addClassRules

$.validator.addClassRules({
     validateRequired: {
         required: true
     },
     validateAlphaonly: {
         alphaOnly: true
     },
     validateNumber: {
         digits: true
     },
     validateDecimalNumber: {
         number: true
     },
     validateEmail: {
         validateEmail: true
     },
     validateURL: {
         url: true
     },
     validatePassword: {
         passwordCheck: true
     },
     validateConfirmPassword: {
         equalTo: '.validatePassword'
     },
     validateMobileNoLimit: {
         minlength: 10,
         maxlength: 10,
         digits: true
     }
 });

Add some addMethod

//password validation (This will match 1 or more uppercase characters, 1 or more lowercase characters and 1 or more 
digit/special character) and at least 8 char
 $.validator.addMethod("passwordCheck", function(value) {
     return /[A-Z]+/.test(value) && /[a-z]+/.test(value) &&
         /[\d\W]+/.test(value) && /\S{8,}/.test(value);
 }, 'Must contain minimum 8 characters including 1 Upper, 1 Lower and 1 or more digit/special char');

 $.validator.addMethod("validateEmail", function(value, element) {
     // allow any non-whitespace characters as the host part
     return this.optional(element) || /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(value);
 }, 'Please enter a valid email address.');

 // regx for alphabet and space
 $.validator.addMethod("alphaOnly", function(value, element) {
     return this.optional(element) || /^[a-z\s]+$/i.test(value);
 }, "Must contain alphabet characters only.");

Write a function for validate form field on submit click

/* function for validate form field on submit click */
 function ValidateAndSubmit(evt) {
     var $group = $(evt.currentTarget).parents('.validateContainer');
     var isValid = true;
     $group.find('.validateField .form-control').each(function(i, item) {
         if (!$(item).valid())
             isValid = false;
     });
     if (!isValid)
         evt.preventDefault();
 }

 /* call 'ValidateAndSubmit' function */
 $('.validateContainer .checkValidationBtn').click(ValidateAndSubmit);

We are done here!

You can use this tutorial for any web-application. Do let me know in case you have any query or feedback by commenting on this post.

Do check out the demo.

Please follow and like us:
Facebook
Google+
http://www.pixpalette.com/jquery-class-based-client-side-validation/
Twitter
Pinterest
LinkedIn

Pixpalette Team

We Create Minimalistic Cool Web stuff. Our passion is all about creating real elegant looking websites. Always keeping it clean and simple with that added functionally of user interaction you would like to see

August 12, 2017

Leave a Reply

Your email address will not be published. Required fields are marked *

Social media & sharing icons powered by UltimatelySocial

Enjoy this blog? Please spread the word :)

  • Facebook
  • Google+
    http://www.pixpalette.com/jquery-class-based-client-side-validation/
  • Twitter
  • Pinterest
  • LinkedIn