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
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
- <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
- <script type="text/javascript" src="Validation.js"></script>
- <form id="newfrm"> <input type="text" id="txtInput" name="txt" /> <input type="submit" value="submit" /> </form>
File: Validation.js
- var validator = $('#newfrm').validate({
- ignoreTitle: true,
- errorPlacement: function(error, element) {
- element.attr('title', error.text());
- }
- });
- $.validator.addMethod('rule1', function(value, element) {
- var isValid = false;
- var regex = /^[a-zA-Z ]*$/;
- isValid = regex.test($(element).val());
- $(element).css({
- "border": "1px solid red",
- "background": "#FFCECE"
- });
- return isValid;
- }, 'Rule 1, failed!');
- $.validator.addMethod('rule2', function(value, element) {
- var isValid = false;
- if ($.trim($(element).val()) == '') {
- isValid = true;
- }
- return isValid;
- }, 'Rule 2, failed!');
-
- $('#txtInput').rules('add', {
- rule1: true,
- rule2: true
- });
- });
I hope this blog might have given some basic idea on implementing common jQuery library to use it in multiple HTML/ aspx forms.