In The craft
Lightweight jQuery Mobile validation plugin
Recently I needed a validation plugin for jQuery Mobile. I tried the existing plugins, but I could not get them to work. I quickly wrote one that served my purpose. It’s very simple. Currently it only supports required fields. I looked into expanding it, but have not needed it. Please use it however you see fit.
Usage:
$("form#loginForm").validate();
Plugin:
(function ($) {
$.fn.validate = function () {
var items = $(this).find('[class~="required"]');
var isValid = true;
items.each(function () {
var self = $(this);
self.blur(function () {
var field = $(this);
if (field.val().length == 0) {
isValid = false;
var siblings = field.siblings('label[class~="field-validation-invalid"]');
if (siblings.length == 0) {
var error = $('<label>')
.addClass('field-validation-invalid field-validation-error')
.text('This field is required');
field.after(error);
}
} else {
var errorMessage = field.siblings('label[class~="field-validation-invalid"]').get(0);
errorMessage = $(errorMessage);
errorMessage.remove();
errorMessage.text('');
}
});
});
var buttons = $(this).find('[type="submit"]');
buttons.each(function () {
var button = $(this);
button.click(function () {
//reset the value, otherwise it's stuck in false mode forever.
isValid = true;
items.each(function () {
var self = $(this);
self.blur();
});
if (!isValid) {
return false;
}
});
});
};
})(jQuery);