Reputation: 1551
I was working on a html form where I have to enter user information and on submit. It will navigate to the php connection page. The problem is that I have been trying to validate the data before submitting through JavaScript and it's not happening.
Below I am posting the HTML form code.
<!DOCTYPE html>
<html>
<head>
<script language = "JavaScript">
function validate()
{
var username = document.getElementById("userName").value;
var password = document.getElementById("Password").value;
var repassword = document.getElementById("RePassword").value;
if (username.length < 0) {
alert("Please enter the username.");
return false;
}
if (password == null || password == "") {
alert("Please enter the password.");
return false;
}
if (repassword == null || repassword == "" || repassword != password) {
alert("Please enter the password.");
return false;
}
}
</script>
</head>
<body>
<form name="frmMr" action="send_post.php" method="post" onsubmit="return(validate());">
User Name:<br> <input type="text" name="userName"><br>
Enter Password:<br> <input type="text" name="Password"><br>
Reenter Password:<br> <input type="text" name="RePassword"><br>
<input type="submit" >
</form>
<p id="error_para" ></p>
</body>
</html>
Upvotes: 1
Views: 10301
Reputation: 1089
I would also suggest using required
attribute for inputs in HTML5.
<input type="text" id="userName" name="userName" required>
It marks the field to be required (as the name says) and the form won't submit if there is no value in it.
Upvotes: 2
Reputation: 12391
You forgot to add IDS to all the fields
<input type="text" name="userName" id="userName">
and so...
Upvotes: 2
Reputation: 1072
Your HTML didn't have id
tag, whereas in Javascript you are using getElementById('')
<!DOCTYPE html>
<html>
<head>
// Changed the script syntax
<script type="text/javascript">
function validate() {
var username = document.getElementById("userName").value;
var password = document.getElementById("Password").value;
var repassword = document.getElementById("RePassword").value;
if (username.length <= 0) {
alert("Please enter the username.");
return false;
}
if (password == null || password == "") {
alert("Please enter the password.");
return false;
}
if (repassword == null || repassword == "" || repassword != password) {
// Changed Password message for testing
alert("Confirm Password empty or do not match.");
return false;
}
}
</script>
</head>
<body>
<form name="frmMr" action="send_post.php" method="post" onsubmit="return(validate());">
User Name:<br> <input type="text" id="userName" name="userName"><br>
Enter Password:<br> <input type="text" id="Password" name="Password"><br>
Reenter Password:<br> <input type="text" id="RePassword" name="RePassword"><br>
<!-- Added id="" attribute to above 3 lines -->
<input type="submit" >
</form>
<p id="error_para" ></p>
</body>
</html>
Upvotes: 3