我正在尝试运行表单验证脚本后设置重定向。但是,当我单击“提交”时,它会抛出一个错误,要求输入有效的电子邮件错误,然后重定向以跳过我的验证检查。
目前,我已经尝试在js文件底部添加函数。但是它重定向而没有运行验证。
HTML
<button class="popup-button" onclick="openForm()">Open Form</button>
<div class="form-popup" id="form">
<form id="form" onsubmit="return formValidate(event)">
<p>
<input type="text" id="e-mail" placeholder="Email" />
</p><p>
<input type="password" id="pswd" placeholder="Password" />
</p>
<br>
<input id="submitButton" type="submit" class="submit"
onclick="redirect()">
<br>
<button type="button" class="btn cancel"
onclick="closeForm()">Close</button>
</form>
JS
function formValidate(event) {
event.preventDefault();
var form = document.getElementById('form');
var email = document.getElementById('e-mail').value;
var password = document.getElementById('pswd').value;
var emailRGEX = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var emailResult = emailRGEX.test(email);
//validate Email
if(emailResult == false){
alert("Please enter a valid email address");
return false;
}
//validate lower case
var lowerCaseLetters = /[a-z]/g;
if(password.match(lowerCaseLetters) == null) {
alert("Password needs a lower case!");
return false;
}
//validate upper case
var upperCaseLetters = /[A-Z]/g;
if(password.match(upperCaseLetters) == null){
alert("Password needs an upper case!");
return false;
}
//validate numbers
var numbers = /[0-9]/g;
if(password.match(numbers) == null){
alert("Password needs a number!");
return false;
}
//validate special characters
var special = /[!@#$%^&*(),.?":{}|<>]/g;
if(password.match(special) == null){
alert("Password needs a special character!");
return false;
}
//validate password length
if(password.length<8) {
alert("Password needs to be at least 8 characters");
return false;
}
form.submit();
}
function redirect(){
window.location.href="thankyou.html";
}
我希望表单在执行验证检查后重定向到我的thankyou.html页面。
答案 0 :(得分:0)
将重定向放在form.submit之前的验证功能中
答案 1 :(得分:0)
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="b.html" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
请找到给出的示例。
并确保您的b.html也位于同一文件夹中。如果要从javascript调用另一个html,请使用window.location.href = url;。成功验证之后。
希望这会对您有所帮助。谢谢