Define form validation. Write example of basic form validation.
Form validation is the process of checking that the data entered into a form meets certain requirements and is in the correct format. It is done to ensure the accuracy and security of the data, and to prevent errors and security vulnerabilities.
Example: validate name,email password, confirm password using onclick(0 & onsubmit() file handling function
Form validation using onclick() file handling event
<html>
<head>
<title>form validation</title>
<script>
function validateForm() {
// Get form values
var name = document.forms["myForm"]["name"].value;
var email = document.forms["myForm"]["email"].value;
var password = document.forms["myForm"]["password"].value;
var confirmpassword=document.forms["myForm"]["confirmpassword"].value;
// Validate
if (name == ""|| email==""||password=="") {
alert("It should not be empty");
return false;
}
if(password==confirmpassword)
{
return true;
}else{
alert("password mismatch");
}
}
</script>
</head>
<body>
<form id="myForm" >
Name:<input type="text" id="name" name="name"><br><br>
Email:<input type="email" id="email" name="email"><br><br>
Password:<input type="password" id="password" name="password"><br><br>
Confirm Password:<input type="password" id="confirmpassword" name="confirmpassword"><br><br>
<input type="submit" value="submit" onclick="return validateForm()">
</form>
</body>
</html>
Form validation using onconsubmit() file handling event
<html>
<head>
<title>form validation</title>
<script>
function validateForm() {
// Get form values
var name = document.forms["myForm"]["name"].value;
var email = document.forms["myForm"]["email"].value;
var password = document.forms["myForm"]["password"].value;
var confirmpassword=document.forms["myForm"]["confirmpassword"].value;
// Validate
if (name == ""|| email==""||password=="") {
alert("It should not be empty");
return false;
}
if(password==confirmpassword)
{
return true;
}else{
alert("password mismatch");
}
}
</script>
</head>
<body>
<form id="myForm" onsubmit="validateForm()" >
Name:<input type="text" id="name" name="name"><br><br>
Email:<input type="email" id="email" name="email"><br><br>
Password:<input type="password" id="password" name="password"><br><br>
Confirm Password:<input type="password" id="confirmpassword" name="confirmpassword"><br><br>
<input type="submit" value="submit" >
</form>
</body>
</html>