A 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. The first three lines of Input.html show how to link validation.js and other related jQuery files to validate the 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 the null value in the text box with id txtInput.
File Input.html
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 the 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!');
- //Assign both rules to the text box.
- $('#txtInput').rules('add', {
- rule1: true,
- rule2: true
- });
- });
