Last active
November 6, 2017 15:53
-
-
Save dachinat/5e84ad9673bca747563e85ff7b55401c to your computer and use it in GitHub Desktop.
Localize (customize) form errors native to browsers. (jQuery Plugin)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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