我有一個表單驗證一個字段。警告框出現在一個錯誤和divs改變,但該頁面繼續提交。我需要幫助弄清楚它爲什麼還在繼續。Javascript驗證:網頁仍提交
的Javascript:
function validateFormOnSubmit(theForm) {
var reason = '';
reason += validateName(theForm.signature_name);
if (reason != '') {
document.getElementById('error').innerHTML = "<p>* All fields are required.<br><span style='color:red'><strong><u>Some fields need correction:</u></strong></span></p>" // + reason;
//alert("Some fields need correction:\n" + reason);
return false;
}
return true;
}
function validateName(fld) {
var error = '';
var illegalChars = /\W\s/; // allow letters, numbers, and underscores
if (fld.value == '') {
error = document.getElementById('client_name').innerHTML = "<h2 id='client_name' style='color:red'>Client's Last Name:</h2><br>The required field has not been filled in.";
alert("Do Not Continue");
} else if ((fld.value.length < 2) || (fld.value.length > 15)) {
error = document.getElementById('client_name').innerHTML = "<h2 id='client_name' style='color:red'>Client's Last Name:</h2><br>The name is not long enough.";
alert("Do Not Continue");
} else if (illegalChars.test(fld.value)) {
error = document.getElementById('client_name').innerHTML = "<h2 id='client_name' style='color:red'>Client's Last Name:</h2><br>The name field contains illegal characters.";
alert("Do Not Continue");
}
return error;
}
HTML
<form enctype='multipart/form-data' name='finishJob' id='finishJob' action='finishJob.php' method='POST' onsubmit='return validateFormOnSubmit(this)'>
<table width='95%' class='tablebox'>
<tr><td name='error'></td><td><h2>Upload Signature:</h2></br><input name='uploadedfile' id='uploadedfile' type='file' /></td><td><h2 id='client_name'>Client's Last Name:</h2></br><input type='text' id='signature_name' name='signature_name'></td><td><input type='submit' value='Complete Job' class='link-button'></td></tr>
</table>
</form>
您需要從validateFormOnSubmit()函數返回true/false,但是您要返回一個字符串。 –
@LeeTaylor再看一遍... – epascarello
'reason'正在調用validateName()函數,該函數根據是否有錯誤返回值或不是。然後,if語句正在檢查最後一個函數是否發回任何內容。如果'reason'中有某些內容,if語句應該返回false,否則該語句返回true。我不確定我是否完全明白你在說什麼。你能詳細說明嗎? – Nicole