表单提交时未执行Javascript验证

表单提交时未执行Javascript验证

问题描述:

I have javascript that is trying to validate a form, more specifically the "type=date" part of the form. But for some reason when I submit the form it doesn't even run the script (I think?) and just goes to the page specified in

here is the code

<!-- script to make sure only weekdays are selected -->
<script>
var date = document.querySelector('[type=date]');

function noWeekends(e){

    var day = new Date( e.target.value ).getUTCDay();

    // Days in JS range from 0-6 where 0 is Sunday and 6 is Saturday

    if( day == 0 || day == 6 ){
        e.target.setCustomValidity('Please select a weekday.');
        return false;
    } else {
        e.target.setCustomValidity('');
    }
}
date.addEventListener('input',noWeekends);
</script>
<!--============================================================
=======================form starts here=========================-->

<form action="confirm_booking.php" onsubmit="noWeekends()" method='post'> 
<?php
echo "Room: ";
select_room();
?>
week starting: <input type=date name='WeekStart'/>

<input type="submit" value="Book Room">
</form>

<!DOCTYPE html>
<html>
    <head>
    <meta charset="utf-8" />
    <title></title>
    </head>
    <body>
        <form id="form" action="confirm_booking.php" method='post'> 
        <?php
        echo "Room: ";
        select_room();
        ?>
        week starting: <input id="date" type=date name='WeekStart'/>
        </form>
        <input type="submit" value="Book Room" onclick="noWeekends()">
        <script>
        function noWeekends(){
            var date = document.getElementById('date');
            var day = new Date( date.value ).getUTCDay();
            console.log(day);
            if( day == 0 || day == 6 ){
                date.setCustomValidity('Please select a weekday.');
                return false;
            } else {
                date.setCustomValidity('');
                document.getElementById("form").submit();
            }
        }
        </script>
    </body>
</html>

works as expected

Note: The submit button is OUTSIDE of the form, and when clicked, the script is executed and submits the form programatically, if everything is right.