You need to enable JavaScript to run this app. 使用preventDefault()阻止表单提交后,验证通过如何跳转至其他页面?
优惠活动
大模型
产品
解决方案
定价
更多

使用preventDefault()阻止表单提交后,验证通过如何跳转至其他页面?

问题根因

你调用e.preventDefault()阻止表单默认提交行为后,没有补充验证通过后的主动提交逻辑,同时checkInputs函数没有返回验证结果状态,程序无法判断何时可以跳转。

修复方案

  1. 给checkInputs函数新增验证状态返回值,所有字段校验无错误时返回true,存在错误时返回false
  2. 在表单提交事件监听中判断验证结果,验证通过后主动调用表单的submit()方法完成提交跳转(原生submit()方法不会重复触发submit事件监听,不会出现死循环)

修改后完整JS代码

const form = document.getElementById('form');
const email = document.getElementById('email');
const password = document.getElementById('password');

form.addEventListener('submit', e => {
    e.preventDefault();
    // 校验通过则触发提交跳转
    if(checkInputs()) {
        form.submit();
    }
});

function checkInputs() {
    // 新增验证状态标记,默认校验通过
    let isValid = true;
    // trim去除首尾空白字符
    const emailValue = email.value.trim();
    const passwordValue = password.value.trim();

    if(emailValue === '') {
        setErrorFor(email, '该字段为必填项');
        isValid = false;
    } else if (!isEmail(emailValue)) {
        setErrorFor(email, '邮箱格式不正确');
        isValid = false;
    } else {
        setSuccessFor(email);
    }

    if(passwordValue === '') {
        setErrorFor(password, '该字段为必填项');
        isValid = false;
    } else {
        setSuccessFor(password);
    }

    function setErrorFor(input, message) {
        const formValidate = input.parentElement;
        const small = formValidate.querySelector('small');
        formValidate.className = 'form-validate error';
        small.innerText = message;
    }

    function setSuccessFor(input) {
        const formValidate = input.parentElement;
        formValidate.className = 'form-validate success';
    }

    function isEmail(email) {
        return /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);
    }
    // 返回最终验证状态
    return isValid;
}

可选方案

如果不需要传递表单参数到购物车页面,也可以把form.submit()替换为window.location.href = 'cart.html',直接跳转即可。

内容的提问来源于stack exchange,提问作者Nurul Syafiqah Binti Zulkifli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 18:36:04