Single JQuery File Used For Validation In Multiple HTML Files

Single jQuery file is used for the validation in multiple HTML files. As we all know, validation is very important for any input form, here is a sample for jQuery validation for HTML, which can be used for any number form. The only thing which we need to do is call the jQuery function in each HTML input form.

In the example given below, we can see two files, Input.html and validation.js. First three lines of Input.html shows how to link validation.js and other related jQuery files to make the validation work.

When Submit button is clicked, it will call the validation $('#newfrm').validate and follows the rules set in $('#txtInput').rules('add', { rule1: true, rule2: true });

Rule 1

This is responsible to validate only the text input in the text box with id txtInput.

Rule 2

This is responsible to validate null value in the text box with id txtInput.

File Input.html
  1. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>  
  2. <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>  
  3. <script type="text/javascript" src="Validation.js"></script>  
  4. <form id="newfrm"> <input type="text" id="txtInput" name="txt" /> <input type="submit" value="submit" /> </form>  
File: Validation.js
  1. var validator = $('#newfrm').validate({  
  2.     ignoreTitle: true,  
  3.     errorPlacement: function(error, element) {  
  4.         element.attr('title', error.text());  
  5.     }  
  6. });  
  7. $.validator.addMethod('rule1'function(value, element) {  
  8.     var isValid = false;  
  9.     var regex = /^[a-zA-Z ]*$/;  
  10.     isValid = regex.test($(element).val());  
  11.     $(element).css({  
  12.         "border""1px solid red",  
  13.         "background""#FFCECE"  
  14.     });  
  15.     return isValid;  
  16. }, 'Rule 1, failed!');  
  17. $.validator.addMethod('rule2'function(value, element) {  
  18.     var isValid = false;  
  19.     if ($.trim($(element).val()) == '') {  
  20.         isValid = true;  
  21.     }  
  22.     return isValid;  
  23. }, 'Rule 2, failed!');  
  24. //Assign both rules to the text box.  
  25. $('#txtInput').rules('add', {  
  26. rule1: true,  
  27. rule2: true  
  28. });  
  29. });  
I hope this blog might have given some basic idea on implementing common jQuery library to use it in multiple HTML/ aspx forms.