I have implemented input validation in my HTML form. However, it does not prompt the user in case of any errors and still proceeds to send its data to the test server.
Below is my code:
<html>
<head>
<style>
input {margin: 10px 5px 10px 5px;}
select {margin: 10px 5px 10px 5px;}
</style>
<script language="JavaScript">
function validate(form1)
{ if (form1.name.value == "" || form1.surname.value == "" || form1.email.value == "" || form1.dob.value == "")
{ alert("One of the field is empty.")
form1.firstname.focus()
form1.firstname.select()
form1.lastname.focus()
form1.lastname.select()
form1.email.focus()
form1.email.select()
form1.dob.focus()
form1.dob.select()
return false
}
return true}
</script>
</head>
<body>
<form method="GET" action="http://www.test/cgi-bin/reply.pl"
onSubmit="return validate(this)">
First Name<input type="text" name="firstname"><br>
Last Name<input type="text" name="lastname"><br>
Email Address<input type="email" name="email"><br>
Date of Birth<input type="date" name="dob"><br>
Favourite Sport
<select name="sports"><br>
<option value="athletics">Athletics</option><br>
<option value="basketball">Basketball</option><br>
<option value="cricket">Cricket</option><br>
<option value="football">Football</option><br>
<option value="hockey">Hockey</option><br>
<option value="swimming">Swimming</option><br>
<option value="tennis">Tennis</option><br>
</select><br>
<input type="Submit"> <input type="reset">
</form>
</body>
</html>
The problem is that when you use onsubmit, your code won't call your function until submission. One way to deal with a user submitting a form with a required input blank is using the required element:
<form>
First Name<input type="text" name="firstname" required><br>
<input type="Submit"> <input type="reset">
</form>
https://jsfiddle.net/d43rLno5/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With