HTML Form Validation Using JavaScript

10-08-2019

Do you want to validate your HTML form using JavaScript? Here is the JavaScript program to validate the HTML form contains the name, phone number, email, password, and confirm_password.

HTML Form Validation Using JavaScript

The below HTML form is validated using a function called ValidateForm in JavaScript code.

<html>
 <head>
 <title>Form Validation Using JavaScript</title>
 </head>
 
 <body>
 <center>
 <h2>JavaScript Form Validation</h2>
 <hr>
 <form name="htmlform" onsubmit="ValidateForm()" method="post" action="">
 <label for="fname">Name:*</label>
 <input type="text" name="fname"><br><br>
 <label for="phone">Phone:*</label>
 <input type="number" name="phone"><br><br>
 <label for="email">Email:*</label>
 <input type="email" name="email"><br><br>
 <label for="password">Password:*</label>
 <input type="password" name="password"><br><br>
 <label for="confirm_pass">Confirm Password:*</label>
 <input type="password" name="confirm_pass"><br><br>
 <input type="submit" value="Submit">
 
 </form>
 </center>
 
 <script>
 function ValidateForm()
 {
 var fname=document.htmlform.fname.value;
 var phone=document.htmlform.phone.value;
 var email=document.htmlform.email.value;
 var password=document.htmlform.password.value;
 var confirm_pass=document.htmlform.confirm_pass.value;
 
 
 if(fname.length<3){
 alert("Name must be filled out correctly");
 
 }
 else if(!phone.match(/^\d{10}$/)){
 alert("Phone Number must be 10 digits long");
 
 }
 else if(!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)){
 alert("You have entered an invalid email address!");

}
 else if(!password.match(/^[A-Za-z]\w{7,14}$/)){
 alert("Password Length must be 8-15 characters");
 }
 else if(!confirm_pass.match(password)){
 alert("Password must match each other");
 }
 else{
 alert("Submission Successful");
 }
 
 }
 
 </script>
 </body>
</html>