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

如何在用户未填写必填输入字段时触发Growl提示?

实现表单必填字段的前端验证(带Growl提示)

我来帮你搞定这个需求!下面是一套完整的实现方案,包含HTML、CSS和原生JavaScript,完全符合你的要求:

1. HTML 表单结构

这里以「用户名」作为必填字段示例,你可以根据实际场景替换字段名称或添加更多必填项:

<form id="myForm">
  <div class="form-group">
    <label for="username">用户名(必填):</label>
    <input type="text" id="username" name="username" placeholder="请输入用户名">
  </div>
  <button type="submit">提交表单</button>
</form>

2. Growl 提示的 CSS 样式

我们自定义一个简洁的Growl提示样式,让它在页面右上角平滑弹出并自动消失:

/* Growl 提示框基础样式 */
.growl-notification {
  position: fixed;
  top: 20px;
  right: 20px;
  background-color: #dc3545; /* 红色警示色,可按需修改 */
  color: white;
  padding: 12px 24px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  z-index: 9999;
  animation: slideInRight 0.3s ease-out;
}

/* 弹出动画 */
@keyframes slideInRight {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

/* 消失动画 */
@keyframes fadeOut {
  to {
    opacity: 0;
    transform: translateX(100%);
  }
}

3. JavaScript 核心验证逻辑

监听表单提交事件,检查必填字段是否为空,弹出Growl提示并阻止默认的后端提交:

document.getElementById('myForm').addEventListener('submit', function(e) {
  // 先阻止表单默认提交行为
  e.preventDefault();
  
  // 获取必填字段的值,去除首尾空格
  const username = document.getElementById('username').value.trim();
  
  // 检查字段是否为空
  if (!username) {
    // 创建Growl提示元素
    const growl = document.createElement('div');
    growl.className = 'growl-notification';
    growl.textContent = '请填写必填字段:用户名';
    
    // 添加到页面
    document.body.appendChild(growl);
    
    // 3秒后自动移除提示框(带消失动画)
    setTimeout(() => {
      growl.style.animation = 'fadeOut 0.3s ease-out forwards';
      setTimeout(() => {
        document.body.removeChild(growl);
      }, 300);
    }, 3000);
    
    // 如果有多个必填字段,可在这里扩展循环检查逻辑
    return;
  }
  
  // 若所有必填项都已填写,这里可添加实际提交逻辑(你要求不提交后端,所以注释掉)
  // fetch('/your-submit-url', { method: 'POST', body: new FormData(this) })
  //   .then(res => res.json())
  //   .then(data => console.log(data));
});

额外小提示

  • 如果有多个必填字段,可以把所有必填项的ID存入数组,循环遍历检查每个字段是否为空,然后弹出对应的提示内容。
  • 提示框的样式(颜色、位置、动画)都可以根据你的UI需求自由调整。
  • 这个方案用原生JS实现,不依赖任何框架,兼容性覆盖绝大多数现代浏览器。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:59:52