I am trying to give validation to both fields email and name but only email is getting validated and its not checking for name field. I am not able to find what is wrong in the code.
<html>
<body>
<form name="myForm">
Email: <input type="text" name="email" id="email2">
<br>
Name: <input type="text" name=" fname">
<button type="submit" name="submit" onclick="validateForm()">submit</button>
<br> email
<div id="email1"></div>
</form>
</body>
<script>
function validateForm() {
var x = document.forms["myForm"]["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;
}
var email1 = document.getElementById("email2").value;
document.getElementById("email1").innerHTML=email1;
var y = document.forms["myForm"]["fname"].value;
if (y==null ||y=="") {
alert("name must be filled");
return false;
}
}
</script>
</html>
You have missed giving id to Name: <input type="text" name=" fname">
Assign ID to Name: <input type="text" name=" fname" id="fname">
.
As document.forms["myForm"]["fname"].value;
this requires element id to fetch value.
<input type="text" name=" fname">
fname前面有一个空格,这就是为什么它不起作用的原因。您可以尝试这样的简单解决方案
Add an additional boolean to check your validation
function validateForm() {
var x = document.forms["myForm"]["email"].value;
//Additional boolean
var success = true;
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");
success = false;
}
var email1= document.getElementById("email2").value;
document.getElementById("email1").innerHTML=email1;
var y = document.forms["myForm"]["fname"].value;
if (y==null ||y=="") {
alert("name must be filled");
success = false;
}
return success;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.