Validation in Javascript for Registration Form


Form Validation Using Javascript for Registration

In this tutorial, we will learn the validation in javascript for registration form. Sometimes, HTML forms in web pages or any other forms are built to prevent the users to submit the form data to know whether the data or information entered by the users are correct or not.

If the information is correct then the form will allow the user to proceed further. We can do this with the help of javascript event handler.

Also Read, auto calculate the sum of input values with javascript

Required Steps of validating a HTML form using Javascript

  • We will use the onsubmit event to validate the input fields and onsubmit event occurs after form data is submitted and it is handled by the web browser.
  • We will use the name attribute of the form and the name attribute of the input fields and combine both the attributes to get the input values.
  • Now, we will store it in a variable and check whether the variable is empty or not. If empty then we can validate the input fields as shown below
var fname = document.forms["userform"]["fname"].value;
		if(fname == ''){
			window.alert('Please enter the first name');
			return false;
		}

COMPLETE CODE:-

<html>
<head>
<title>Form validation using javascript for registration form</title>
</head>
<body>
   <h2 align="center">Registration Form</h2>
   <center>
   	<form name="userform" action="#" onsubmit="return validateUserForm()" method="post">
	  <label for="fname">First name:</label><br>
	  <input type="text" name="fname"><br>
	  <label for="lname">Last name:</label><br>
	  <input type="text" name="lname"><br>
	  <label for="fname">Phone No:</label><br>
	  <input type="text" name="phone_no"><br>
	  <label for="email">Email:</label><br>
	  <input type="email" name="email"><br>
	  <label for="password">Password:</label><br>
	  <input type="password" name="password"><br><br>
	  <input type="submit" value="Submit">
	</form>
  </center>
</body>
<script type="text/javascript">
	function validateUserForm(){
		var fname = document.forms["userform"]["fname"].value;
		if(fname == ''){
			window.alert('Please enter the first name');
			return false;
		}
		var lname = document.forms["userform"]["lname"].value;
		if(lname == ''){
			alert('Please enter the Last name');
		}
		var phone_no = document.forms["userform"]["phone_no"].value;
		if(phone_no == '' || isNaN(phone_no)){
			alert('Please enter the valid Phone No');
		}
		var email = document.forms["userform"]["email"].value;
		if(email == ''){
			alert('Please enter the email address');
		}
		var password = document.forms["userform"]["password"].value;
		if(password == ''){
			alert('Please enter the password');
		}
	}
</script>
</html>

Conclusion:- I hope this tutorial will help you to understand the form validation using javascript for registration form.


Leave a Comment