Bootstrap 验证失败时表单不会取消提交

Bootstrap form doesn't cancel submission when validation failed

我正在尝试创建一个表单,该表单会在提交时向用户发送电子邮件。

问题是我使用了 Bootstrap 的表单模板,当我用 phone 提交它并邮寄错误的值(phone 数字甚至为空)时,电子邮件已发送无论如何(200 ok)并且显示成功警报。

这是我的 HTML 代码:

<form class="needs-validation" novalidate id="paymentForm">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="firstName">First Name</label>
                                <input type="text" class="form-control" name="firstName" id="firstName" placeholder="" value="" required>
                                <div class="invalid-feedback">
                                    required Feild
                                </div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="lastName">Lasr Name</label>
                                <input type="text" class="form-control" name="lastName" id="lastName" placeholder="" value="" required>
                                <div class="invalid-feedback">
                                    required Feild
                                </div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="email">Email</label>
                            <input type="email" class="form-control" value="" name="email" id="email" placeholder="you@example.com" required>
                            <div class="invalid-feedback">
                                please enter a valid mail address
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="phone">Phone Number</label>
                            <input type="tel" class="form-control" value="" name="phone" placeholder="example: 050-1111111" pattern="[0]{1}[5]{1}[0-9]{8}" id="phone" required>
                            <div class="invalid-feedback">
                                please provide a valid phone number
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="address"> address</label>
                            <input type="text" class="form-control" name="address" id="address" placeholder="" required>
                            <div class="invalid-feedback">
                              please provide your address
                            </div>
                        </div>
                        <hr class="mb-4">

                        <h4 class="mb-3">payment method</h4>
                        <div class="d-block my-3">
                            <div class="custom-control custom-radio">
                                <input id="cash" value="cash" value="cash" name="paymentMethod" type="radio" class="custom-control-input" required checked>
                                <label class="custom-control-label" for="cash">cash</label>
                            </div>
                            <div class="custom-control custom-radio">
                                <input id="bit" value="bit" value="bit" name="paymentMethod" type="radio" class="custom-control-input" required>
                                <label class="custom-control-label" for="bit">Bit</label>
                            </div>
                        </div>
                        <div class="invalid-feedback">
                            please choose method
                        </div>

                        <hr class="mb-4">
                        <button class="btn btn-primary btn-lg btn-block" type="submit">continue to checkout</button>

                    </form>

这是我的 js:

(function() {
    'use strict'
    window.addEventListener('load', function() {       
        var forms = document.getElementsByClassName('needs-validation')       
        Array.prototype.filter.call(forms, function(form) {
            form.addEventListener('submit', function(event) {

                var radioValue = $('#paymentForm input:radio:checked').val()
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated')
                var orderNumber = generateId();
                var cName = $('#firstName').val() + " " + $('#lastName').val()
                var cEmail = $('#email').val()
                var cPhone = $('#phone').val()
                var cAddress = $('#address').val()
                var cSumToPay = parseInt(localStorage.getItem("totalPrice"));
                var cProducts = JSON.parse(localStorage.getItem("products") || "[]");
                cProducts = cProducts.map(Object.values);                   
                cProducts = cProducts.join(' ');
                console.log(cProducts);
                var templateParams = {
                    order_number: orderNumber,
                    customer_name: cName,
                    products: cProducts,
                    addres: cAddress,
                    phone: cPhone,
                    customer: cEmail,
                    payment_Methode: radioValue,
                    customer_sum: cSumToPay
                };
                emailjs.send('gmail', 'orderconfirmation', templateParams)
                    .then(function(response) {
                        console.log('SUCCESS!', response.status, response.text);
                        alert('Yey! Your email was sent :)');           
                    }, function(error) {
                        console.log('error');
                        alert(error);
                    });
                event.preventDefault();
            }, false)
        })
    }, false)

}())

如果你们能帮助我,我将不胜感激!!!

这部分似乎是您唯一的验证检查:

            if (form.checkValidity() === false) {
                event.preventDefault();
                event.stopPropagation();
            }

但是,event.preventDefault()event.stopPropagation() 不会阻止代码进入下一节。您可以通过在此处包含 return

来做到这一点
            if (form.checkValidity() === false) {
                event.preventDefault();
                event.stopPropagation();
                return false;
            }

或者您可以将其余代码包装在条件

else
            if (form.checkValidity() === false) {
                event.preventDefault();
                event.stopPropagation();
            } else {
                // your email handling code
            }

注意:您的 event.preventDefault() 可用于阻止提交按钮执行其提交表单的默认行为,并且 event.stopPropagation() 只会阻止事件冒泡到父元素(您可能不需要)。参见:https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault and https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation

在任何情况下,如果您在事件侦听器的顶部放置一个调用,则不需要两次 event.preventDefault() 调用,例如

form.addEventListener('submit', function(event) {
    event.preventDefault();
    ...