I'm still relatively a beginner in JS, so this likely is just me not having that great fundamentals in the language.
I'm trying to create timestamp objects (think youtube timestamps, but with a title instead of just the time) using a very simple HTML form, validated before sending the post request.
To submit the form I intentionally do not use JQuery or an inline event handler, as I would like to use an eventListener. However with an eventListener, even when the form is invalid, the form is still submitted.
HTML and javascript excerpts with some variables replaced with placeholders below:
# 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;
}
Where is my mistake?
I was originally using an inline event handler there onsubmit="return validateForm()", but for best practice reasons and to be able to disallow inline javascript via CSP I would like to move away from that.
Answers to other questions to this that I found either refer to JQuery or use inline event handlers, both of which I would like to avoid. Lastly one recommended passing the validation-function directly to the eventListener instead of creating an anonymous function, which I tried (see comments above) and it didn't work.