How to create validate html form using javascript | javascript form validation with source code

Sami
0

How to create validate html form using javascript | javascript form validation with source code



To create form validation using JavaScript, you can follow these steps:

How to create validate html form using javascript | javascript form validation with source code
How to create validate html form using javascript | javascript form validation with source code

Step 1: HTML Markup

First, create an HTML form with the necessary input fields and a submit button. Assign unique name to each input element to easily access them using JavaScript. Add an <span> element after each label to display the required sign (*)for validation .

HTML

<div>
	<form name="ff" onsubmit="show()">
	<label>Name</label><span style="color: red;">*</span>
	<input name="fname" type="text" />
	<label>Email</label><span style="color: red;">*</span>
	<input name="femail" type="eamil" />
	<label>Password</label><span style="color: red;">*</span>
	<input name="fpass" type="password" />
	<label>Confirm password</label><span style="color: red;">*</span>
	<input name="cpass" type="password" />
	<button>submit</button>
</form>
</div>

Step 2 : CSS style 

second, apply the required style on all the required input fields and labels for better design. 
Here you can apply any desired CSS style in your HTML Form. 


CSS

<style type="text/css">
		div{
			width: 500px;
			margin: auto;
			box-shadow: 0 0 10px black;
			padding: 20px;
		}
		input{
			width: 90%;
			margin: 10px 1px;
		}
	</style>

Step 3: JavaScript Validation

Add a script tag in your HTML File where JavaScript  function to handle form validation. You can use the (document.form_name.input_name.value) method to access the form elements data and validate their values. All the javascript function will be activate after click on the submit button.
Display the error with the alert() function in Javascript. 

JAVASCRIPT

<script type="text/javascript">
function show(){
	var nameData = document.ff.fname.value;
	var emailData = document.ff.femail.value;
	var passData = document.ff.fpass.value;
	var cpassData = document.ff.cpass.value;
	if (nameData=="" && emailData=="" && passData=="" && cpassData=="") {
		alert("all fields are empty")
	}
	else if (nameData==""){
		alert("name is empty ")
	}
	else if (emailData==""){
		alert("email is empty ")
	}
	else if (passData==""){
		alert("password is empty ")
	}
	else if (cpassData==""){
		alert("confirm password  is empty ")
	}
	else if (passData!=cpassData){
	alert("password and confirm password are not equal")
	}
	else{
		alert("done")
	}

	}
</script>


Post a Comment

0Comments
Post a Comment (0)