Blog » JavaScript » java script form validation

java script form validation

This tutorial will show you how to create form validation using JavaScript. JavaScript is usefulness for data validation when user clicks on the button, an alert dialog box appears if invalid data has been entered. you cannot submit empty filed. only after all data is approved is the form submitted.

html form


<form id="form" name="form" method="post" action="validation.html" onsubmit="return validationRegister()">
<p><label>Name:<br />
<input name="name" type="text" id="name" /></label></p>
<p><label>Email:<br />
<input name="email" type="text" id="email" /></label></p>
<p><label>Password:<br />
<input name="Password" type="password" id="Password" /></label></p>
<p><label>Confirm Password:<br />
<input name="ConfPassword" type="password" id="ConfPassword" /></label></p>
<p><input type="submit" name="Submit" value="Submit" /></p>
</form>


JavaScript code


<script>
function validationRegister(){
if(document.getElementById("name").value == ""){
alert("Enter name");
document.getElementById("name").focus();
return false;
}
if(document.getElementById("email").value == ""){
alert("Enter email address");
document.getElementById("email").focus();
return false;
}
var email = document.getElementById("email").value;
var atpos = email.indexOf("@");
var dotpos = email.lastIndexOf(".");
var len = email.length;
if(atpos < 2 || dotpos-atpos < 3 || len-dotpos < 3){
alert("Enter a valid email address");
document.getElementById("email").focus();
return false;
}
if(document.getElementById("Password").value == ""){
alert("Enter password");
document.getElementById("Password").focus();
return false;
}
if(document.getElementById("ConfPassword").value != document.getElementById("Password").value){
alert("Confirm password do not match");
document.getElementById("Password").focus();
return false;
}
return true;
}
</script>
ARTICLE POSTED BY : Admin

Hi, I'am k.g uththara. I'm a professional web developer. I write blog posts in my free time. if you want to contact me, send a message on contact page, thanks.