我有一個簡單的表單,正在驗證onchange並需要最終驗證onsubmit。我在錯誤的輸入框右側顯示一條消息。我試圖保持DOM 1兼容。提交的JavaScript表單驗證
HTML
<form id = "myForm" action = "" onsubmit = "return validateForm(this);">
<table class = "table-submit" border = "0">
<tr>
<td>
Username:
</td>
<td>
<input type = "text" id = "username"
size = "30" maxlength = "30"
onchange = "validateUsername(this, 'msgUsername')" />
</td>
<td id = "msgUsername">
</td>
</tr>
<tr>
<td>
Password:
</td>
<td>
<input type = "password" id = "password"
size = "30" maxlength = "30"
onchange = "validatePassword(this, 'msgPassword')" />
</td>
<td id = "msgPassword">
</td>
</tr>
<tr>
<td> </td>
<td>
<input type = "submit" value = "Submit" />
<input type = "reset" value = "Clear" />
</td>
</tr>
</table>
</form>
的JavaScript
function validateUsername(myItem, myElement) {
var dom = document.getElementById(myElement);
if (myItem.value.length < 3) {
dom.innerHTML = " Username needs to be a minimum of 3 characters! ";
return false;
}
else {
dom.innerHTML = "";
return true;
}
}
function validatePassword(myItem, myElement) {
var dom = document.getElementById(myElement);
if (myItem.value.length < 5) {
dom.innerHTML = " Password needs to be a minimum of 5 characters! ";
return false;
}
else {
dom.innerHTML = "";
return true;
}
}
function validateForm (itm) {
// kind of stuck here...
}
正如你可能注意到的,我堅持我的validateForm()函數位。 代碼驗證每個輸入框onchange事件。 不知道什麼是從這裏去的最佳途徑。我想過如果爲我的兩個單一輸入框驗證,但我需要發送每個參數,這是我試圖避免使用這個。 想要一些建議。
http://jsfiddle.net/W4g4e/7/ – gibberish 2014-10-07 01:35:04