我有一个html表单,我使用javascript来验证它。我想要
全部,但我仍然无法做到:(
这里是我的所有代码
<html>
<head>
<script type="text/javascript">
function verifyNull(){
if(!document.getElementById('username').value.trim().length){
alert('Please enter username');
}
else if(!document.getElementById('password').value.trim().length){
alert('Please enter password');
}
}
function verifyEmail(){
var x = document.getElementById('email').value;
var atpos = x.indexOf("@");
var dotpos = x.lastIndexOf(".");
if (atpos< 1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;
}
}
</script>
<title>Bài 2</title>
</head>
<body>
<form name = "myForm" method = "post" action = "registerd.html">
Username <input type = "text" id = "username" name = "username"/><br />
Password <input type = "password" id = "password" name = "password" /> <br />
Email <input type = "text" id = "email" name = "email"/>
<input type = "submit" value = "Submit" onClick = "verifyNull();verifyEmail();"/>
</form>
</body>
答案 0 :(得分:2)
通常,如果验证成功,验证函数应返回true, 如果验证失败,则返回false。
function perform()
{
if(isValid)
{
return true;
}
else
{
return false;
}
}
在上面的代码中,方法verifyNull()和verifyEmail()应该返回true或false。按如下所示更改代码,并在表单的提交上调用validate()方法。
Remove the onclick event from the submit button and add an onsubmit event to the form.
<form name="myForm" action="registerd.html" onsubmit="return validate()">...</form>
function validate()
{
return (verifyNull() && verifyEmail());
}
function verifyNull(){
var isValid = true;
if(!document.getElementById('username').value.trim().length){
isValid = false;
alert('Please enter username');
}
else if(!document.getElementById('password').value.trim().length){
isValid = false;
alert('Please enter password');
}
return isValid;
}
function verifyEmail(){
var x = document.getElementById('email').value;
var atpos = x.indexOf("@");
var dotpos = x.lastIndexOf(".");
if (atpos< 1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;
}
return true;
}
答案 1 :(得分:1)
使用if else
声明。假设有一个变量告诉你验证是否通过,称为formValidation
:
if(formValidation === true) {
window.open("path/to/page.html", "_self");
} else {
// Do something else (the validation failed)
}
要提供更详细的答案(如果需要),则需要提供更多代码。
答案 2 :(得分:0)
HTML: -
<form onsubmit="return validation()">
.....
</form>
使用JavasScript: -
<script>
function validation() {
var isValid = true;
//perform your validation on form and update isValid variable accordingly.
if(isValid) {
window.location = ''; // your desired location
}
return false; // always return false to prevent form from submission.
}
</script>