Custom and Easy Javascript Form Validation With Example(New)

Custom and Easy Javascript Form Validation With Example(New)

Custom and Easy Javascript Form Validation With Example(New)

What is javascript form validation:

Javascript form validation is most important part of web development where you can display custom errors message to users and visitors of your website. We used Javascript form validation to collect user's information and displaying custom error messages to users when they enter wrong data into the form fields.

In the following section we will take a closer look at how to perform JavaScript form validation.

Form Validation with JavaScript

The custom form validation process consists of two parts

  • Required field’s validation which is performed to make sure that all the mandatory fields are filled.
  •  Data format validation which is performed to ensure that the type and format of the data entered in the form is valid.

 Let's add a form first before working on the validation part.

STEPS

We need to follow the following steps below to create our web page;

  1. Launch your text editor and create a new file and save it as "index.html" in your development folder.
  2. Write down the standard HTML5 tags used in defining a HTML document in "index.html" file. Example;
<html>

  <head>

    <title> Custome Form validation using javascript </title>

  </head>

<body>

   

</body>

</html>

In order to make your html form fields beautiful we need to use bootstrap classes. For using bootstrap classes you need to add the minified versions of bootstrap libraries on your webpage between head tag. For example

<link href=" path/to/bootstrap.min.css" rel="stylesheet">

<script src=" path/to/bootstrap.min.js" type="text/javascript"></script>

Now we create a complete html form for custom javascript validation using javascript functions:

<!DOCTYPE html>
<html>
	<head>
		<title>Custome Form validation using javascript</title>
			<link href="css/bootstrap.min.css" rel="stylesheet">
			<link rel="stylesheet" type="text/css" href="css/style.css"/>
		
	</head>
		<body>
			<div class="container">
				<h1>Custome Form validation using javascrip</h1>
					
					<form name="myForm" onsubmit="return validateForm()">
					<div class="form-group">
						<label>Your Name</label> <span id="error-name"></span>
						<input type="text" id="your-name" class="form-control" placeholder="Enter your Name">
					</div>
					<div class="form-group"> 
						<label>Your Email</label> <span id="error-email"></span>
						<input type="email" id="your-email" class="form-control" placeholder="Enter your Email">
					</div>
					<div class="form-group"> 
					<label>Select the Country</label><span id="error-country"></span>
				<select id="country1" class="form-control" onchange="country();" placeholder="Enter your Country Name">
						<option value=""></option>
						<option value="+92">Pak</option>
						<option value="+93">USA</option>
						<option value="+94">UK</option>
						<option value="96">Australia</option>
				</select>
				</div>
					<div class="form-group">
						<label>Your Phone</label> <span id="error-phone"></span>
						<input type="text" id="your-phone" class="form-control"  onchange="country2();"placeholder="Enter your Phone">
					</div>
					<div class="form-group">
						<label>Your Message</label> <span id="error-message"></span>
						<textarea id="your-message" class="form-control" rows="10" placeholder="Enter your Message"></textarea>
					</div>
					<div class="form-group">
						<input type="submit" class="btn btn-info" value="Submit"><span id="error-sub"></span>
					</div>
					
				</form>
			</div>		
					
	<script src="js/bootstrap.min.js" type="text/javascript"></script>
	<script src="js/javascript.js" type="text/javascript"></script>
		</body>
</html>

Here, we created a form using bootstrap classes and added a javascript functions to be initialized on the event of form submission. We also added an empty id beside the labels for each form field where we'll display the error message.

Building the Form Validation Script

Now we're going to create a JavaScript file that holds our complete validation script.

Well, let's create a JavaScript file named "javascript.js" and place the following code inside it, then save it at the same location where you've saved the previous HTML file. Go through each line of the following example code to understand how JavaScript validation works:

Javascript source code to validate our html form.


function validateForm(){
	var name = document.getElementById('your-name').value;
	var email = document.getElementById('your-email').value;
	var phone = document.getElementById('your-phone').value;
	var message = document.getElementById('your-message').value;
	var country = document.getElementById('country1').value;
	if (name.length<5) {
        document.getElementById('error-name').innerHTML = " Please Enter Your Name *"
    }
    if (email.length<1) {
        document.getElementById('error-email').innerHTML = " Please Enter Your Email *";
    }
    if (phone.length<1) {
        document.getElementById('error-phone').innerHTML = " Please Enter Your Phone *";      
    }
    if (message.length<1) {
        document.getElementById('error-message').innerHTML = " Please Enter Your Message *";
    }
	if (country.length<1) {
        document.getElementById('error-country').innerHTML = " Please Select Your Country Name *";
    }	
    if(name.length<1 || email.length<1 || phone.length<1 || message.length<1 || country.length<1){
		document.getElementById("error-sub").innerHTML="form submit unsuccesfuly";
       	return false;
    }
else{
	document.getElementById("error-sub").innerHTML="Form submit Succesfuly";
	
}	
}
function country(){
	var val3=document.getElementById("country1").value;
	document.getElementById("your-phone").value=val3;
}
function country2(){
var code1=document.getElementById("country1").value;
alert(code1);
}
	

Function validateForm() which is programmed to initialize on form submission, we created individual variable to store input values from each of the form fields. Then, we checked the string length of each of the values. If any of those form field values have no texts inside it, then, their respective error ids will display the defined texts inside it with the javascript pre-built function document.getElementById() To prevent the form from being submitted in case of any error, we used OR statement to return the user back to the same page without further processing of data at the end.

Add some Custom css to beautify the Form and Error messges.

Finally, create the file named "style.css" and place the following code in it, then save it also at the same location where you've saved the previous two files.


h1{
	color:red;text-decoration:underline;margin-left: 260px;
	}

#error-name {
  color: red;
  margin-left: 5px;
}

#error-email {
  color: red;
  margin-left: 5px;
}
#error-phone {
  color: red;
  margin-left: 5px;
}
#error-message {
  color: red;
  margin-left: 5px;
}
#error-country{
  color: red;
  margin-left: 5px;
}
#error-sub{
  color: red;
  margin-left: 5px;
}
form{
	margin-left:100px;
}

We hope you may learn how to use javascript custom validation. Please share your queryies in the comment section below or contact us.

Click here to download full source code