You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过addEventListener实现表单验证后POST提交?

实现表单验证通过后POST提交到指定地址

第一步:修改HTML表单配置

原表单缺少提交地址、请求方法,且输入框没有name属性(无name的输入框数据不会被携带到提交请求中),需要补充这些关键属性:

修改后的HTML代码:

<div class="container">
<div class="header">
    <h2>创建账号</h2>
</div>
<form id="form" class="form" action="/postdata" method="POST">
    <div class="form-control">
        <label for="username">用户名</label>
        <input type="text" placeholder="florinpop17" id="username" name="username" />
        <i class="fas fa-check-circle"></i>
        <i class="fas fa-exclamation-circle"></i>
        <small>错误提示</small>
    </div>
    <div class="form-control">
        <label for="email">邮箱</label>
        <input type="email" placeholder="a@florin-pop.com" id="email" name="email" />
        <i class="fas fa-check-circle"></i>
        <i class="fas fa-exclamation-circle"></i>
        <small>错误提示</small>
    </div>
    <div class="form-control">
        <label for="password">密码</label>
        <input type="password" placeholder="Password" id="password" name="password"/>
        <i class="fas fa-check-circle"></i>
        <i class="fas fa-exclamation-circle"></i>
        <small>错误提示</small>
    </div>
    <div class="form-control">
        <label for="password2">确认密码</label>
        <input type="password" placeholder="再次输入密码" id="password2" name="password2"/>
        <i class="fas fa-check-circle"></i>
        <i class="fas fa-exclamation-circle"></i>
        <small>错误提示</small>
    </div>
    <button>提交</button>
</form>
</div>

核心修改:

  • 给<form>标签添加action="/postdata"(指定提交地址)和method="POST"(指定请求方法)
  • 每个输入框补充name属性,属性值与id一致,确保表单数据能被正确携带

第二步:修改JS验证逻辑,验证通过后触发提交

原JS仅做验证不返回结果,需要调整逻辑让它返回验证状态,再在提交事件中判断是否触发表单默认提交:

修改后的JS代码:

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

form.addEventListener('submit', e => {
    e.preventDefault();
    
    // 验证通过则触发表单默认提交
    if(checkInputs()) {
        form.submit();
    }
});

function checkInputs() {
    // 去除首尾空格
    const usernameValue = username.value.trim();
    const emailValue = email.value.trim();
    const passwordValue = password.value.trim();
    const password2Value = password2.value.trim();
    // 标记是否所有验证通过
    let isValid = true;
    
    if(usernameValue === '') {
        setErrorFor(username, '用户名不能为空');
        isValid = false;
    } else {
        setSuccessFor(username);
    }
    
    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);
    }
    
    if(password2Value === '') {
        setErrorFor(password2, '请再次输入密码');
        isValid = false;
    } else if(passwordValue !== password2Value) {
        setErrorFor(password2, '两次输入的密码不一致');
        isValid = false;
    } else{
        setSuccessFor(password2);
    }
    
    // 返回最终验证结果
    return isValid;
}

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

function setSuccessFor(input) {
    const formControl = input.parentElement;
    formControl.className = 'form-control 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);
}

核心修改:

  • 在checkInputs中新增isValid变量,初始为true,只要有一项验证失败就设为false
  • checkInputs函数最后返回isValid状态
  • 提交事件监听中,判断验证通过后调用form.submit()触发表单默认提交
  • 把错误提示文本改为中文,适配国内使用场景

修改完成后,当所有字段通过客户端验证时,表单会自动将数据POST到/postdata地址,同时服务端仍可进行二次验证保障数据安全。

内容的提问来源于stack exchange,提问作者Segev Solomon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 05:45:56