Javascript 验证失败时重定向用户
我在使用JS验证表单时遇到一些问题 这是HTMLJavascript 验证失败时重定向用户,javascript,php,Javascript,Php,我在使用JS验证表单时遇到一些问题 这是HTML <form action="xyz.php" method="post"> <div class="form-group"> <label class="sr-only" for="id1">Enter ID</label> <input type="text" class="form-control" name="id1" id="id1"> </div&
<form action="xyz.php" method="post">
<div class="form-group">
<label class="sr-only" for="id1">Enter ID</label>
<input type="text" class="form-control" name="id1" id="id1">
</div>
<button onclick="validateID()" type="submit" name="submit" class="btn">Submit</button>
</form>
输入ID
提交
这是JS
<script>
function validateID() {
var id = document.getElementById("id1").value;
var reg1 = new RegExp("^([0-9][0-9][0-9])$");
if (!(reg1.test(id))) {
document.location.href= "http://www.errorpage.com";
}
}
</script>
函数validateID(){
var id=document.getElementById(“id1”).value;
var reg1=新的RegExp(“^([0-9][0-9][0-9])$”;
如果(!(reg1.test(id))){
document.location.href=”http://www.errorpage.com";
}
}
它应该根据正则表达式检查提交的表单值,如果验证失败,它必须重定向到错误页面
但是,它不会重定向。当我将alert()放在document.location.href=”的位置时http://www.errorpage.com";代码>它可以工作
非常感谢您的帮助。我想这与位置无关。这是因为按钮类型是submit,表单执行默认操作并将表单提交到xyz.php。这就是为什么当他发出警报时。它起作用了
改变
提交
尝试window.location.href或location.href
详细原因:
函数validateID(){
var id=document.getElementById(“id1”).value;
var reg1=新的RegExp(“^([0-9][0-9][0-9])$”;
如果(!(reg1.test(id))){
document.location.href=”http://www.errorpage.com";
返回true;
}否则{
返回false;
}
}
输入ID
提交
你能试试window.location.hrefi吗?我想这与location.href无关。这是因为按钮类型是submit,表单执行默认操作并将表单提交到xyz.php。这就是为什么当他发出警报时。它起作用了。请参考下面我的答案,所以需要返回0;在location.href之后?只是好奇,JS不应该在
之后吗?编辑:好的,现在知道了!它是如何工作的?浏览器是否保存了validateID()函数,以便在以后单击按钮时使用?嗯,每次提交表单时都使用validateID();功能。
<html>
<head>
<script>
function validateID() {
var id = document.getElementById("id1").value;
var reg1 = new RegExp("^([0-9][0-9][0-9])$");
if (!(reg1.test(id))) {
document.location.href = "http://www.errorpage.com";
return true;
}else{
return false;
}
}
</script>
</head>
<body>
<form action="xyz.php" method="post" onsubmit="event.preventDefault(); validateID();">
<div class="form-group">
<label class="sr-only" for="id1">Enter ID</label>
<input type="text" class="form-control" name="id1" id="id1">
</div>
<button type="submit" name="submit" class="btn">Submit</button>
</form>
</body>
</html>