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

如何使用JavaScript实现表单输入校验,不使用required等原生属性

JavaScript表单校验实现方案

你可以通过通用校验函数+循环遍历的方式避免重复代码,具体实现如下:

function validate() {
    // 按顺序对应4个输入框,序号对应提示id的后缀
    const inputs = [
        document.getElementById('email'),
        document.getElementById('old_password'),
        document.getElementById('new_password'),
        document.getElementById('confirm_password')
    ]
    let allValid = true

    // 通用单输入框校验逻辑
    function validateInput(input, index) {
        const val = input.value.trim()
        const suffix = index + 1 // 提示id后缀从1开始
        // 获取对应提示元素
        const fillTip = document.getElementById(`fill_field_${suffix}`)
        const lenTip = document.getElementById(`minium_8_characters_${suffix}`)
        const spaceTip = document.getElementById(`cant_contain_space_${suffix}`)

        // 先默认隐藏所有提示
        fillTip.style.display = 'none'
        lenTip.style.display = 'none'
        spaceTip.style.display = 'none'

        let valid = true
        // 按优先级校验:空值>长度不足>包含空格
        if (val === '') {
            fillTip.style.display = 'block'
            valid = false
        } else {
            if (val.length < 8) {
                lenTip.style.display = 'block'
                valid = false
            }
            if (val.includes(' ')) {
                spaceTip.style.display = 'block'
                valid = false
            }
        }
        return valid
    }

    // 遍历校验所有输入框
    inputs.forEach((input, idx) => {
        const inputValid = validateInput(input, idx)
        if (!inputValid) allValid = false
    })

    // 校验两次密码是否一致
    const pwdMatchTip = document.getElementById('error')
    pwdMatchTip.style.display = 'none'
    if (allValid) {
        const newPwd = document.getElementById('new_password').value
        const confirmPwd = document.getElementById('confirm_password').value
        if (newPwd !== confirmPwd) {
            pwdMatchTip.style.display = 'block'
            allValid = false
        }
    }

    // 所有校验通过后,执行你自己的表单提交逻辑
    if (allValid) {
        document.getElementById('form').submit()
    }
}

逻辑说明

  • 所有输入框的校验逻辑都复用同一个validateInput函数,不需要为每个输入框单独写校验规则
  • 校验优先级按空值、长度不足、包含空格依次判断,避免同一输入框同时弹出多个冗余提示
  • 所有输入框基础校验通过后,才会判断两次密码是否一致,减少无效校验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 10:18:04