gpt4 book ai didi

javascript - HTML 表单 JS 验证

转载 作者:行者123 更新时间:2023-11-30 14:53:39 24 4
gpt4 key购买 nike

我正在尝试验证我的登录表单,以便在将值发布到我的 PHP 文件之前该字段将具有最小/最大长度。

JavaScript:

function loginValidation() {
var user = document.login.username.value;
var pass = document.login.password.value;

if (user.length <= 6 || user.length > 20) {
alert("Please make sure the username is between 7 and 20 characters.");
return false;
}

if (pass.length <= 8 || pass.length > 50) {
alert("Please make sure the password field is between 9 and 50 characters.");
return false;
}
}

HTML:

<form name="login" onsubmit="loginValidation()" action="login.php" method="post">
<div class="form-group row">
<label for="username" class="lead para col-sm-4">Username</label>
<input type="text" class="form-control transparent col-sm" id="username" name="username" placeholder="Username">
</div>
<div class="form-group row">
<label for="password" class="lead para col-sm-4">Password</label>
<input type="password" class="form-control col-sm" id="password" name="password" placeholder="Password">
</div>
<button type="submit" class="btn btn-outline-primary">LOGIN</button>
</form>

似乎代码忽略了函数或者它根本不起作用(可能是错误?)。

其他可能有用的信息是包含我的所有函数的 JavaScript 文件都是外部的。

<script src="/JS/functions.js"></script>

最佳答案

Working fiddle .

您只是在 onsubmit 的函数调用中缺少 return,应该像这样:

<form name="login" onsubmit="return loginValidation()" action="login.php" method="post">
_____________________________^^^^^^

最好将事件附加到您的 JS 部分:

document.querySelector('form[name="login"]').addEventListener("submit", loginValidation);

function loginValidation() {
var user = document.login.username.value;
var pass = document.login.password.value;

if (user.length <= 6 || user.length > 20) {
alert("Please make sure the username is between 7 and 20 characters.");
return false;
}

if (pass.length <= 8 || pass.length > 50) {
alert("Please make sure the password field is between 9 and 50 characters.");
return false;
}
return true;
}
<form name="login" onsubmit="return loginValidation()" action="login.php" method="post">
<div class="form-group row">
<label for="username" class="lead para col-sm-4">Username</label>
<input type="text" class="form-control transparent col-sm" id="username" name="username" placeholder="Username">
</div>
<div class="form-group row">
<label for="password" class="lead para col-sm-4">Password</label>
<input type="password" class="form-control col-sm" id="password" name="password" placeholder="Password">
</div>
<button type="submit" class="btn btn-outline-primary">LOGIN</button>
</form>

关于javascript - HTML 表单 JS 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47723243/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com