In the below example, we can see two files Input.html and validation.js. First 3 lines of Input.html shows how to link validation.js and other related jQuery files to make the validation work.
When the 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 for validating the text only input in the text box with id txtInput.
Rule: 2
This is responsible for validating 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 });
});
No comments:
Post a Comment