ラベルが入力と同じレベルのDOM階層にあり、マークアップの入力のすぐ隣にあると仮定すると、次のようなことができます。
まず、HTMLの例をいくつか示します。
<html>
<body>
<form onsubmit="return validation()" action="submit.php" method="post">
<label for="name">Name:</label>
<input type="text" value="" id="name" />
<label for="email">Email:</label>
<input type="text" value="" id="email" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
ご覧のとおり、すべての入力の前には、正しい属性を持つラベルが付いています。
さて、Javascriptについては、頭の中で説明します。
<script type="text/javascript">
function validation() {
//So we have a validation function.
//Let's first fetch the inputs.
name = document.getElementById("name");
email = document.getElementById("email");
//The variable error will increment if there is a validation error.
//This way, the form will not submit if an error is found.
error = 0;
//Now for validation.
if(name.value.length < 6) {
//We've found an error, so increment the variable
error++;
//Now find the corresponding label.
nameLabel = name.previousSibling;
//If we found the label, add an error class to it.
if(nameLabel && nameLabel.for = name.id) {
nameLabel.className = "error";
}
}
///////////////////
//Do the same with the email...
///////////////////
//Now, if there are no errors, let the form submit.
//If there are errors, prevent it from doing so.
return (error == 0) ? true : false;
}
</script>
次に、CSSを追加します。
<style type="text/css">
.error {
background-color: red;
}
</style>
編集-この種のソリューションは必要なかったと思いますが、サーバーに移動する前に検証する必要がある場合は、ここに移動します。:)