Skip to content

Instantly share code, notes, and snippets.

@dachinat
Last active November 6, 2017 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dachinat/5e84ad9673bca747563e85ff7b55401c to your computer and use it in GitHub Desktop.
Save dachinat/5e84ad9673bca747563e85ff7b55401c to your computer and use it in GitHub Desktop.
Localize (customize) form errors native to browsers. (jQuery Plugin)
/**
* Local forms jQuery plugin.
* Author: Dachi Natsvlishvili
*/
(function($) {
$.fn.local_forms = function(options) {
var handle = function(key, e) {
if (!e.validity.valid) {
$.each(options[key], function(key, value) {
if (e.validity[key]) {
value = value.replace("$input", $(e).val());
e.setCustomValidity(value);
}
});
}
}
if (!$(this).is("form")) {
throw ".local_forms has to be called on a form."
}
$.each(options, function(key) {
var e = $.find(key)[0];
$(e).on("invalid", function(){
handle(key, e)
});
$(e).on("input change", function() {
e.setCustomValidity("");
handle(key, e);
});
});
}
return this;
}(jQuery));
/**
* Usage example
*/
$(document).ready(function(){
$("#form").local_forms({
"#form_first_name": {
valueMissing: "Value is missing" // Assuming input has required attribute
},
"#form_personal_id": {
valueMissing: "Value is missing",
patternMismatch: "Pattern mismatch" // Assuming input has pattern attribute
},
"#form_email": {
valueMissing: "Value is missing",
typeMismatch: "Type mismatch" // Assuming input type is email
}
});
});
// Validity states can be found at https://developer.mozilla.org/en-US/docs/Web/API/ValidityState
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment