如何同时展示所有表单验证错误,而非逐个弹出提示框
表单一次性展示所有校验错误的纯JS实现方案
原生HTML5表单默认的校验逻辑是遇到第一个校验不通过的字段就终止校验,仅弹出该字段的提示,因此会出现逐个提示的问题。你可以通过自定义校验逻辑实现一次性展示所有错误,完整实现如下:
完整可运行代码
<html lang="zh-CN"> <head> <title>表单校验示例</title> <meta content="width=device-width, initial-scale=1" name="viewport" /> <style> .error_message { color: #f5222d; font-size: 12px; margin: 4px 0 0 0; min-height: 16px; } .mandatory { color: #f5222d; margin-left: 2px; } </style> </head> <body> <!-- 添加novalidate属性禁用浏览器默认校验提示 --> <form id="mainForm" action="#" method="POST" novalidate> <div> <div> <label for="first_name" title="first_name">名字<span class="mandatory">*</span></label> <input id="first_name" name="first_name" type="text" value="" required placeholder="请输入名字"> <p class="error_message"></p> </div> <div> <label for="lastName" title="lastName">姓氏<span class="mandatory">*</span></label> <input id="lastName" name="lastName" type="text" value="" required placeholder="请输入姓氏"> <p class="error_message"></p> </div> <div class=""> <input class="email_btn btn btn-block" type="submit" value="提交"> </div> </div> </form> <script> document.addEventListener('DOMContentLoaded', function() { const form = document.getElementById('mainForm'); // 配置各字段的错误提示 const fieldErrorMap = { first_name: '请输入名字', lastName: '请输入姓氏' }; form.addEventListener('submit', function(e) { let hasInvalidField = false; // 先清空所有历史错误提示 document.querySelectorAll('.error_message').forEach(el => el.textContent = ''); // 遍历所有必填字段逐一校验 form.querySelectorAll('input[required]').forEach(input => { const fieldValue = input.value.trim(); if (!fieldValue) { hasInvalidField = true; // 找到当前字段对应的错误容器写入提示 input.nextElementSibling.textContent = fieldErrorMap[input.id]; } // 可在此处扩展其他校验规则,比如长度、格式校验等 // 例:if (fieldValue.length < 2) { 写入长度不够的提示 } }); // 存在校验不通过的字段则阻止表单提交 if (hasInvalidField) { e.preventDefault(); } }); }); </script> </body> </html>
核心逻辑说明
- 给form标签添加
novalidate属性,关闭浏览器自带的默认校验弹窗,避免和自定义提示冲突 - 监听表单的submit事件,触发校验前先清空所有历史错误提示,避免重复展示
- 遍历所有带
required属性的输入框,逐一判断是否符合校验规则,所有不通过的字段都会同步显示对应错误 - 仅当所有字段都校验通过时,才会正常提交表单
内容的提问来源于stack exchange,提问作者Noel M.
相关产品推荐
相关产品推荐

