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 make a loop on all your input elements that's why you obtain the same result in each element. Give an id to your input for example username and password, then try :
$(document).ready(function() {
var msg="";
var elements = document.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("");
switch(e.target.id){
case "password" :
msg="Bad password";
case "username" :
msg="Username cannot be blank";
}
if (!e.target.validity.valid) {
e.target.setCustomValidity(msg);
}
};
elements[i].oninput = function(e) {
e.target.setCustomValidity("");
};
} })
You can use this code.
<input type="text" required="" name="username" placeholder="Username" oninvalid="this.setCustomValidity('Username cannot be blank')"> <input type="password" required="" name="password" placeholder="Password" oninvalid="this.setCustomValidity('Password cannot be blank')">
sorry, some mistakes in my code. Try that, that works for me :
$(document).ready(function() {
var msg="";
var elements = document.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid =function(e) {
if (!e.target.validity.valid) {
switch(e.target.id){
case 'password' :
e.target.setCustomValidity("Bad password");break;
case 'username' :
e.target.setCustomValidity("Username cannot be blank");break;
default : e.target.setCustomValidity("");break;
}
}
};
elements[i].oninput = function(e) {
e.target.setCustomValidity(msg);
};
}
})
You may add an id
attribute to both your username and password input
elements:
<input placeholder="Username" required id="username" />
<input type="password" placeholder="Password" required id="password" />
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.