我有一個HTML表單,其中包含一些圖像的文本字段和文件輸入。它具有文本所需的字段,它還對使用JavaScript(jQuery)選擇的圖像進行了一些客戶端驗證。如何防止JavaScript form.submit()忽略必填字段
這裏是形式:
<form name="addbookform" id="addbookform" action="processaddbook.php" method="POST">
<p />
<input name="name" id="name" type="text" placeholder="Name" required />
<p />
<textarea name="description" id="description" cols=30 rows=4 placeholder="Enter a short description">
</textarea>
<p />
<input name="image" id="image" type="file" accept="image/png, image/jpeg" />
<p />
<input type="button" id="finishbutton" value="Submit" />
</form>
做我寫了一些JavaScript代碼(使用jQuery)圖像客戶端檢查,並將其鏈接到finishbutton
。
$(document).ready(function() {
$('#finishbutton').click(function() {
var fileInput = document.getElementById("bookimage");
if (fileInput.value == "") {
// We can just submit the form without an image.
addbookform.submit();
} else {
// Check for image size and other properties...
if (success == true) {
addbookform.submit();
}
}
});
});
現在圖像檢查工作正常(報告錯誤或圖像有效),但是,也有在窗體上的name
輸入必填字段。當圖像檢查通過(或沒有圖像),提交函數被調用,但它似乎像HTML已跳過所需的字段驗證。
有沒有辦法來防止這種情況?
我會使用普通的'type = submit'按鈕,然後使用$(「#addbookform」)。on(「submit」,...)'做任何額外的驗證,防止提交如果圖像驗證失敗,否則只是允許默認的提交行爲繼續。 – nnnnnn