gpt4 book ai didi

javascript - 即使验证正则表达式错误也提交表单

转载 作者:行者123 更新时间:2023-11-29 10:09:09 25 4
gpt4 key购买 nike

当我提交密码和用户名都错误的表单时,我遇到了这个问题。我收到一个警告框,提示我输入了错误的详细信息。但是当用户名正确并且密码验证错误时,它会在按下确定时给我一个 arlet 框,即使我返回 false,它也会提交表单。请帮助非常感谢

<script type="text/javascript">
function validate(form_id, firstName, password){
var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = document.forms[form_id].elements[firstName].value;
var password = document.forms[form_id].elements[password].value;

if (Reg.test(username) == false) {
alert('Invalid Username.');
document.forms[form_id].elements[firstName].focus();
return false;
}

if (Reg1.test(password) == false) {
alert('Invalid Password.');
document.forms[form_id].elements[password].focus();
return false;
}
}
</script>

<form id="form_id" action="userlogininput.cgi" onsubmit="javascript:return validate('form_id','firstName','password');" name="form" method="post">
Username : <input type="text" id="firstName" name="firstName" class="textboxH-300" required><br>
Password : <input type="password" id="password" name="password" class="textboxH-300" required><br><br>
<input id="submitbtn" type="submit" value="Submit"/>
</form>

最佳答案

您可以使用 e.preventDefault() 来阻止表单发送。

这是一个代码示例

(function(){    
function validate(e) {

e.preventDefault(); // prevent the form sending


var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = document.getElementById('firstName');
var password = document.getElementById('password');

if (Reg.test(username.value) == false) {
alert('Invalid Username.');
username.focus();
return false;
}

if (Reg1.test(password.value) == false) {
alert('Invalid Password.');
password.focus();
return false;
}
}

//add event listener for form submission
document.getElementById('form_id').addEventListener('submit',validate);
})();
<form id="form_id" action="userlogininput.cgi" name="form" method="post">
Username :
<input type="text" id="firstName" name="firstName" class="textboxH-300" required>
<br> Password :
<input type="password" id="password" name="password" class="textboxH-300" required>
<br>
<br>
<input id="submitbtn" type="submit" value="Submit" />
</form>

关于javascript - 即使验证正则表达式错误也提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36821378/

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