问题
I'm trying to make fields required but I want the error to show up next to the field it self not be alert?
回答1:
You can put validation messages near inputs you wanna validate like
<span class="reqMsg">* First name is required</span>
Of course you need to hide them at first with css
.reqMsg {
color:red;
display:none;
}
Then in your form submit function you can change your relevant code to this
var valid = true;
var firstFocus = null;
for (var i = 0; i < rules.length; i++) {
if (!rules[i][1]) {
valid = false;
var parent = elem(rules[i][0]).parentNode;
parent.children[2].style.display = "inline";
if (firstFocus == null) firstFocus = parent.children[1];
}
}
if (!valid) {
firstFocus.focus();
return false;
}
return true;
You can see that it's not returning false immediately if one field is not valid. It checks all the fields then set a focus to first element of those that are not valid.
FIDDLE
回答2:
Add span tag next to input tag
<span id="first-name-err"></span>
and change you javascript code as below
function alpha(e) {
var k;
document.all ? k = e.keyCode : k = e.which;
return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8);
}
var flag = true;
for (var i = 0; i < rules.length; i++) {
alert(rules[i][0]);
if (!rules[i][1]) {
var parent = elem(rules[i][0]).parentNode,
message = 'Please check your ' + (parent.textContent || parent.innerText).replace(/^\s*(.*?)\s*$/, '$1').slice(0, -1).toLowerCase() + '.';
var id = rules[i][0]+'-err';
document.getElementById(rules[i][0]+'-err').innerHTML = message;
flag = false;
}
}
return flag;
};
check this
来源:https://stackoverflow.com/questions/23510490/how-to-show-a-required-message-next-to-input-with-javascript