I would like two different messages in two field, for example, the username and password field that contain messages like \"username cannot be blank\" and \"password cannot be b
You may add an id
attribute to both your username and password input
elements:
Then you may use a switch
statement to add the custom validation message according to the target of the event:
$(document).ready(function () {
var elements = document.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function (e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
switch (e.srcElement.id) {
case "username":
e.target.setCustomValidity("Username cannot be blank");
break;
case "password":
e.target.setCustomValidity("Password cannot be blank");
break;
}
}
};
elements[i].oninput = function (e) {
e.target.setCustomValidity("");
};
}
})
Here's a demo.