这是我的代码
我正在尝试制作一个注册表格,我制作了一个剧本
我试过用户名应包含字母和数字,而不包含任何其他内容
如果此条件为真,则继续 否则它将在其下方显示错误消息
<html>
<head>
</head>
<body>
<style>
#sign_up_details {
padding: 10px;
}
</style>
<form name="sign_up_details">
<h3>Enter your details below</h3>
<input type="textbox" id="username" placeholder="Enter your desired username" />
<p id="usrnm_check"></p><br>
<input type="password" id="password" placeholder="Enter your desired password" />
<p id="pass_check"></p><br>
<input type="textbox" id="email" placeholder="Enter your email id" />
<p id="email_check"></p><br>
<input type="submit" name="submit" value="Submit" onclick="store()" />
</form>
<script>
var usrnm = document.getElementById("username");
var pass = document.getElementById("password");
var email = document.getElementById("email");
var usrnm_check = document.getElementById("usrnm_check");
var pass_check = document.getElementById("pass_check");
var email_check = document.getElementById("email_check");
function store() {
var newReg = /^[A-Z]+[a-z]+[0-9]+$/
if (usrnm.value.match(newReg)) {
//next action here
} else {
usrnm_check.innerHTML = "Username should have alphabets and numbers";
}
}
</script>
</body>
</html>
例如,当我将用户名字段保持为空并单击提交时,将显示的错误位于其下方,但很快就会消失。 我不知道它的原因。
答案 0 :(得分:1)
您必须在onsubmit事件中设置商店,而不是在提交按钮onclick事件上设置商店,因为onclick将执行该功能并提交表单。
这里是小提琴
execute function before submit
<html>
<head>
</head>
<body>
<style>
#sign_up_details {
padding: 10px;
}
</style>
<form name="sign_up_details" onsubmit="return store()">
<h3>Enter your details below</h3>
<input type="textbox" id="username" placeholder="Enter your desired username" />
<p id="usrnm_check"></p><br>
<input type="password" id="password" placeholder="Enter your desired password" />
<p id="pass_check"></p><br>
<input type="textbox" id="email" placeholder="Enter your email id" />
<p id="email_check"></p><br>
<input type="submit" name="submit" value="Submit" />
</form>
<script>
var usrnm = document.getElementById("username");
var pass = document.getElementById("password");
var email = document.getElementById("email");
var usrnm_check = document.getElementById("usrnm_check");
var pass_check = document.getElementById("pass_check");
var email_check = document.getElementById("email_check");
function store() {
var newReg = /^[A-Z]+[a-z]+[0-9]+$/
if (usrnm.value.match(newReg)) {
//next action here
return true;
} else {
usrnm_check.innerHTML = "Username should have alphabets and numbers";
return false;
}
}
</script>
</body>
</html>
答案 1 :(得分:0)
您可以尝试这样的事情:
id="b"
注意返回true并在store()和onSubmit形式中返回false语句。如果store()将返回false,则表单将不会被提交。目前,您的消息在显示后消失,因为即使验证失败,您的表单也会被提交。
希望这会有所帮助!!