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

如何让纯HTML5登录门户强制用户输入后才可登录?

解决HTML5 required属性不生效的问题

你的required属性没起作用,核心原因是当前登录按钮是被<a>标签包裹的普通按钮,点击时直接跳转链接,完全触发不了HTML5的表单验证机制。要实现必填项验证,必须依托<form>标签和表单提交行为,具体修改如下:

修正方案

  1. 将用户名输入框、密码输入框、登录按钮全部放入<form>标签内部
  2. 给<form>标签设置action属性,指定登录成功后的跳转地址
  3. 将登录按钮改为表单提交按钮(设置type="submit")

修正后的完整代码

<!DOCTYPE html>
<html>   
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title> Login Page </title>  
<style>   
Body {  
  font-family: Calibri, Helvetica, sans-serif;  
  background-color: #30aeb3;
  
}  
button {   
       background-color: #ffffff;   
       width: 100%;  
        color: orange;   
        padding: 15px;   
        margin: 10px 0px;   
        border: none;   
        cursor: pointer;   
         }   
 form {   
        border: 3px solid #ffffff;   
    }   
 input[type=text], input[type=password] {   
        width: 100%;   
        margin: 8px 0;
        padding: 12px 20px;   
        display: inline-block;   
        border: 2px solid green;   
        box-sizing: border-box;   
    }  
 button:hover {   
        opacity: 0.7;   
    }   
  .cancelbtn {   
        width: auto;   
        padding: 10px 18px;
        margin: 10px 5px;
    }   
        
     
 .container {   
        padding: 25px;   
        background-color: lightblue;
    }   
</style>   
</head>    
<body>
  <h1 style="text-align:center;"> Logon Utility </h1>
<form action="https://lovableignorantparticle.chaitanyakuraku.repl.co/">
  <div class="container">
    <label for="uname"><b>Username</b></label>
    <input type="text" placeholder="Enter Username" name="uname" required>

    <label for="psw"><b>Password</b></label>
    <input type="password" placeholder="Enter Password" name="psw" required >

    <label>
      <input type="checkbox" checked="checked" name="remember"> Remember me
    </label>
  </div>
    <div class="container">
        <button type="submit" class="btn btn-primary btn-lg">Logon?</button>
    </div>
</form>
</body>
</html>  

原理说明

点击type="submit"的按钮时,浏览器会自动校验表单内所有带required属性的输入框:

  • 若有未填写的必填项,浏览器会弹出提示并阻止表单提交
  • 所有必填项填写完成后,才会跳转到form标签action属性指定的地址

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 04:47:10