假設標籤與輸入的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>
編輯 - 我猜你不希望這種解決方案,但是如果你想在去服務器之前驗證它,那麼你就去。 :)
感謝您的評論。後端驗證已經處理完畢,但我想讓前端更友好。我編輯了我的問題。 – l15a 2008-12-31 16:56:54