As we all know that there is no uniformity in the form element validation messages comes in different browsers. To make these error messages uniform, we can set custom error message so that all browser displays the same error message.
This solution is not full proof however it works in most modern browser except Internet Explorere 10.
First we have created a simple form with a textbox, email and url textbox.
<form action="somepage.html" method="post"> <fieldset> <legend>Login</legend>Name: <input type="text" id="myName" name="myName" required placeholder="Please enter your name" data-error="Name is required" />* <br /> Email: <input name="myEmail" id="myEmail" type="email" required placeholder="Enter email" data-error="Email is required in you@domain.com" /> <br /> Url: <input type="url" id="myUrl" name="myUrl" /> <input type="submit" id="mySubmit" name="mySubmit" /> </fieldset> </form>
In the above all other element and its attributes are normal except the data-error attribute. Attribute starts with "data-" is a special type of attribute introduced in HTML 5 that can be used to hold that element specific data. It doesn't have any meaning to the browser. It is used only for the developer to hold some temporary data.
In this case, we are holding our custom error message into the data-error attribute.
Now write following jQuery code (Do not forget to refer the jQuery file into the page).
<script>
$(function () {
var inputs = document.getElementsByTagName("INPUT");
for (var i = 0; i < inputs.length; i++) {
inputs[i].oninvalid = function (e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity(e.target.getAttribute("data-error"));
}
};
}
});
</script>
In the above jQuery code we are doing following
OUTPUT
NOTE
If data-error attribute is not specified for a particular element, few browser like Firefox may display "null" is the element is invalid (like in this case, notice that we do not have data-error attribute in the URL textbox). So it is suggested to always set data-error attribute to each input type element.
Views: 20822 | Post Order: 100