【发布时间】:2020-09-16 10:12:12
【问题描述】:
我还是 JS 的初学者,所以这可能只是我没有很好的语言基础。
我正在尝试使用一个非常简单的 HTML 表单创建时间戳对象(想想 youtube 时间戳,但使用标题而不是时间),在发送发布请求之前进行验证。
为了提交表单,我故意不使用 JQuery 或内联事件处理程序,因为我想使用 eventListener。但是使用 eventListener,即使表单无效,表单仍然会被提交。
HTML 和 javascript 摘录,其中一些变量替换为下面的占位符:
# piece of timestamp_create_form.html
<h3> New Timestamp </h3>
<form class="timestamp-form" name="timestamp-form" action="URL_PLACEHOLDER" method="POST" enctype="multipart/form-data">
<input type="hidden" name="csrfmiddlewaretoken" value="TOKEN_PLACEHOLDER">
<div class="input-row">
<div>
<input type="text" maxlength="100" id="id_name" placeholder="Timestamp-Title" class="input-title" name="name">
<label for="name"> Timestamp-Title </label>
</div>
<div>
<input type="text" id="id_time" maxlength="8" value="00:00:00" name="time" class="input-time">
<label for="time"> Time </label>
</div>
</div>
<div class="form-buttons">
<div><input type="submit" class="btn" value="Create Timestamp"></div>
<div><a class="button" id="cancel-timestamp-creation" href="#"> Cancel </a></div>
</div>
</form>
# timestamp.js
// Add Event Listener to the form for the "onsubmit" event
document.forms['timestamp-form'].addEventListener('submit', function(){ return validateTimestampForm();} );
// I also tried this second variant, it did not work either
// document.forms['timestamp-form'].addEventListener('submit', validateTimestampForm);
function validateTimestampForm(){
const timestampForm = document.forms['timestamp-form'];
const timestamp_time_string = timestampForm['time'].value;
const hours = parseInt(timestamp_time_string.substring(0,2));
const minutes = parseInt(timestamp_time_string.substring(3,5));
const seconds = parseInt(timestamp_time_string.substring(6,8));
let timestamp_seconds = 3600*hours + 60*minutes + seconds;
if (timestamp_seconds > 7200){
alert("The time you entered is past the duration of the audio file!");
return false;
}
const timestamp_name = timestampForm['name'].value;
if (timestamp_name === ""){
alert("Timestamp title must be filled out!");
return false;
}
return true;
}
我的错误在哪里?
我最初在 onsubmit="return validateForm()" 使用内联事件处理程序,但出于最佳实践原因以及能够通过 CSP 禁止内联 javascript,我想放弃它。
我发现其他问题的答案是指 JQuery 或使用内联事件处理程序,我希望避免这两种情况。最后一个建议将验证函数直接传递给 eventListener,而不是创建一个匿名函数,我尝试过(参见上面的 cmets)但没有成功。
【问题讨论】:
标签: javascript html forms