jQuery validation
Testing jQuery validation
by litespeedtdf
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mockjax/1.6.2/jquery.mockjax.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<form id="jForm" method="post" novalidate="novalidate">
<p>
<label for="desc">Your Description (required)</label>
<input id="desc" name="desc">
</p>
<p>
<button id="jSubmit" name="jSubmit" type="submit">Submit</button>
<label id="ljSubmit" for="jSubmit"></label>
</p>
</form>
CSS
/*!
* jQuery UI CSS Framework 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/category/theming/
*
* To view and modify this theme, visit...
JavaScript
$(document).ready(function() {
$.mockjax({
url: 'testing.action',
//type: 'POST',
response: function(settings) {
var desc = settings.data.desc;
var descs = ["glen", "george", "me"];
this.responseText = "true";
if ($.inArray(desc, descs) !== -1) {
this.responseText = "false";
//var ff = $('#jForm').validate();
// validator.showErrors({
// "desc": "I know that your firstname is Pete, Pete!"
// });
}
},
responseTime: 500
});
// validate jForm on keyup and submit
var validator = $('#jForm').validate({
rules: {
desc: {
required: true,
maxlength: 10
// remote: 'testing.action'
}
},
messages: {
desc: {
required: "Enter a description",
maxlength: jQuery.validator.format("Max length is {0}.")
//,remote: 'error'
//testing: "failed!!"
}
}, // the errorPlacement has to take the table layout into account
errorPlacement: function(error, element) {
error.appendTo(element.parent());
},
onfocusout: function(element, event) {
//validator.showErrors({
// desc: 'testing'
// });
validator.form();
//return false;
}, // specifying a submitHandler prevents the default submit, good for the demo
submitHandler: function() {
alert("submitted!");
}, // set this class to error-labels to indicate valid fields
success: function(label) {
//alert("success!");
// set as text for IE
label.html(" ").addClass("ui-icon ui-icon-circle-check");
},
highlight: function(element, errorClass) {
$(element).next('#desc-error').removeClass("ui-icon ui-icon-circle-check");
}
});
/*
validator.element('#desc');
validator.showErrors: ({
"desc": "New error message"
});
*/
});