How to validate html form using javascirpt?

JavaScript Form Validations.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("form").submit(function(){
alert("Submitted");
});
});
</script>

It is important to validate the form submitted by the user because it can have inappropriate values. So validation is must. The JavaScript provides you the facility the validate the form on the client side so processing will be fast than server-side validation. So, most of the web developers prefer JavaScript form validation. Through JavaScript, we can validate name, password, email, date, mobile number etc fields.

File name : index.php

File Name:- index.php

<html> <head> <title>Form Validation</title>
<script type="text/javascript">
<!-- // Form validation code will come here. //-->
</script>
<script type="text/javascript">

function validate() {
if( document.myForm.Name.value == "" )
{ alert( "Please provide your name!" );
$("#Name").focus();
document.myForm.Name.focus() ;
return false; }
if( document.myForm.EMail.value == "" )
{ alert( "Please provide your Email!" ); document.myForm.EMail.focus() ;
return false; }
if( document.myForm.Zip.value == "" || isNaN( document.myForm.Zip.value ) || document.myForm.Zip.value.length != 5 )
{ alert( "Please provide a zip in the format #####." ); document.myForm.Zip.focus() ;
return false; } if( document.myForm.Country.value == "-1" )
{ alert( "Please provide your country!" );
return false; }
return( true );
}
</script>
< /head>
<body>
<form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr> <td align="right">Name</td> <td><input type="text" name="Name" /></td> </tr>
<tr> <td align="right">EMail</td> <td><input type="text" name="EMail" /></td> </tr>
<tr> <td align="right">Zip Code</td> <td><input type="text" name="Zip" /></td> </tr>
<tr> <td align="right">Country</td> <td> <select name="Country"> <option value="-1" selected>[choose yours]</option>
<option value="1">USA</option> <option value="2">UK</option> <option value="3">INDIA</option>
</select> </td> </tr>
<tr> <td align="right"></td> <td><input type="submit" value="Submit" /></td> </tr>
</table>
</form>
</body>
</html>

How to validate userid and password with alert message.

File name : index.php

<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;

if (name==null || name==""){
alert("Name can't be blank");
$("#name").focus();
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
$("#password").focus();
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="abc.php" onsubmit="return validateform()" >
Name: <input type="text" id="name" name="name"><br/>
Password: <input type="password" id="password" name="password"><br/>
<input type="submit" value="register">
</form>

Name Validation Example.

File name : index.php

<html>
<head>
<script type="text/javascript">
function validation() {
var a = document.form.name.value;
if(a=="") {
alert("Please Enter Your Name");
document.form.name.focus();
return false; } }
</script>
</head>
<body>
<form name="form" method="post" onsubmit="return validation()">
<tr> <td>Your Name:</td>
<td><input type="text" name="name""></td> </tr> <tr> <td></td>
<td><input type="submit" name="sub" value="Submit"></td> </tr> </form>
</body>
</html>

Username Validation allows only Characters.

File name : index.php

<html>
<head>
<script type="text/javascript"> function validation() {
var a = document.form.name.value;
if(a=="") {
alert("Please Enter Your Name");
document.form.name.focus();
return false;
}
if(!isNaN(a)){
alert("Please Enter Only Characters");
document.form.name.select();
return false;
}} </script>
</head>
<body>
<form name="form" method="post" onsubmit="return validation()">
<tr>
<td>Your Name:</td> <td><input type="text" name="name""></td> </tr> <tr> <td></td>
<td><input type="submit" name="sub" value="Submit"></td> </tr> </form>
</body>
</html>

Allow only numeric value in input box Validation.

File name : index.php

<html>
<head>
<title>allwon only numbers in textbox using JavaScript</title>
<script language="Javascript" type="text/javascript">

function onlyNos(e, t) {
try {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
catch (err) {
alert(err.Description);
}
}

</script>
</head>
<body>
<table align="center">
<tr>
<td>
<input type="text" onkeypress="return onlyNos(event,this);" />
</td>
</tr>
</table>
</body>
</html>

Allow only alphabets value in input box Validation.

File name : index.php

<html>
<head>
<title>allwon only alphabets in textbox using JavaScript</title>
<script language="Javascript" type="text/javascript">

function onlyAlphabets(e, t) {
try {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))
return true;
else
return false;
}
catch (err) {
alert(err.Description);
}
}

</script>
</head>
<body>
<table align="center">
<tr>
<td>
<input type="text" onkeypress="return onlyAlphabets(event,this);" />
</td>
</tr>
</table>
</body>
</html>

Limited Character Validation.

File name : index.php

<html> <head> <script type="text/javascript"> function validation() { var a = document.form.name.value; if(a=="") { alert("Please Enter Your Name"); document.form.name.focus(); return false; } if(!isNaN(a)) { alert("Please Enter Only Characters"); document.form.name.select(); return false; } if ((a.length < 5) || (a.length > 15)) { alert("Your Character must be 5 to 15 Character"); document.form.name.select(); return false; } } </script> </head> <body> <form name="form" method="post" onsubmit="return validation()"> <tr> <td>Your Name:</td> <td><input type="text" name="name""></td> </tr> <tr> <td></td> <td><input type="submit" name="sub" value="Submit"></td> </tr> </form> </body> </html>

Password Validation.

File name : index.php

<html> <head> <script type="text/javascript"> function validation() { var a = document.form.pass.value; if(a=="") { alert("Please Enter Your Password"); document.form.pass.focus(); return false; } } </script> </head> <body> <form name="form" method="post" onsubmit="return validation()"> <tr> <td>Password:</td> <td><input type="password" name="pass""></td> </tr> <tr> <td></td> <td><input type="submit" name="sub" value="Submit"></td> </tr> </form> </body> </html>

Password Validation allows only Limited Characters or integers.

File name : index.php

<html> <head> <script type="text/javascript"> function validation() { var a = document.form.pass.value; if(a=="") { alert("Please Enter Your Password"); document.form.pass.focus(); return false; } if ((a.length < 4) || (a.length > 8)) { alert("Your Password must be 4 to 8 Character"); document.form.pass.select(); return false; } } </script> </head>
<body> <form name="form" method="post" onsubmit="return validation()"> <tr> <td>Passsword:</td> <td><input type="password" name="pass""></td> </tr> <tr> <td></td> <td><input type="submit" name="sub" value="Submit"></td> </tr> </form> </body> </html>

Email Validation.

File name : index.php

<html> <head> <script type="text/javascript"> function validation() { var a = document.form.email.value; if(a=="") { alert("Please Enter Your Password"); document.form.email.focus(); return false; } } </script> </head> <body> <form name="form" method="post" onsubmit="return validation()"> <tr> <td>Email:</td> <td><input type="text" name="email""></td> </tr> <tr> <td></td> <td><input type="submit" name="sub" value="Submit"></td> </tr> </form> </body> </html>

Email Validation (Email filter /@\ and /.\)

File name : index.php

<html> <head> <script type="text/javascript"> function ValidateContactForm() { var email = document.ContactForm.Email; if (email.value == "") { window.alert("Please enter a valid e-mail address."); email.focus(); return false; } if (email.value.indexOf("@", 0) < 0) { window.alert("Please enter a valid e-mail address."); email.focus(); return false; } if (email.value.indexOf(".", 0) < 0) { window.alert("Please enter a valid e-mail address."); email.focus(); return false; } } </script> </head>
<body> <form name="ContactForm" method="post" onsubmit="return ValidateContactForm();"> <tr> <td>Email:</td> <td><input type="text" name="Email""></td> </tr> <tr> <td></td> <td><input type="submit" name="sub" value="Submit"></td> </tr> </form> </body> </html>

JavaScript Retype Password Validation

File name : index.php

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function matchpass(){
var firstpassword=document.f1.password.value;
var secondpassword=document.f1.password2.value;

if(firstpassword==secondpassword){
return true;
}
else{
alert("password must be same!");
return false;
}
}
</script>
</head>
<body>

<form name="f1" action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return matchpass()">
Password:<input type="password" name="password" /><br/>
Re-enter Password:<input type="password" name="password2"/><br/>
<input type="submit">
</form>

</body>
</html>

JavaScript Number Validation

File name : index.php

<!DOCTYPE html>
<html>
<head>
<script>
function validate(){
var num=document.myform.num.value;
if (isNaN(num)){
document.getElementById("numloc").innerHTML="Enter Numeric value only";
return false;
}else{
return true;
}
}
</script>
</head>

<body>
<form name="myform" action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return validate()" >
Number: <input type="text" name="num"><span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>

</body>
</html>

JavaScript validation with image

File name : index.php

<html>
<body>
<script type="text/javascript">
function validate(){
var name=document.f1.name.value;
var passwordlength=document.f1.password.value.length;
var status=false;
if(name==""){
document.getElementById("namelocation").innerHTML=
" <img src='http://www.javatpoint.com/javascriptpages/images/unchecked.gif'/> Please enter your name";
status=false;
}else{
document.getElementById("namelocation").innerHTML=" <img src='http://www.javatpoint.com/javascriptpages/images/checked.gif'/>";
status=true;
}

if(passwordlength<6){
document.getElementById("passwordlocation").innerHTML=
" <img src='http://www.javatpoint.com/javascriptpages/images/unchecked.gif'/> Password must be greater than 6";
status=false;
}else{
document.getElementById("passwordlocation").innerHTML=" <img src='http://www.javatpoint.com/javascriptpages/images/checked.gif'/>";
}

return status;
}
</script>
<form name="f1" action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return validate()">
<table>
<tr><td>Name:</td><td><input type="text" name="name"/>
<span id="namelocation" style="color:red"></span></td></tr>
<tr><td>Password:</td><td><input type="password" name="password"/>
<span id="passwordlocation" style="color:red"></span></td></tr>
<tr><td colspan="2"><input type="submit" value="register"/> </td></tr>
</table>
</form>
</body>
</html>

EMAIL VALIDATION USING JAVASCRIPT

File name : index.php

<html>
<head>
<script type="text/javascript">
function validation()
{
var a = document.form.email.value;
if(a=="")
{
alert("Please Enter Your Password");
document.form.email.focus();
return false;
}
}
</script>
</head>
<body>
<form name="form" method="post" onsubmit="return validation()">
<tr>
<td> Email:</td>
<td><input type="text" name="email""></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="sub" value="Submit"></td>
</tr>
</form>
</body>
</html>

Email Validation (Email filter /@\ and /.\)

File name : index.php

<html><head><script type="text/javascript"> function validation(){ var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i var b=emailfilter.test(document.form2.mailid.value); if(b==false){ alert("Please Enter a valid Mail ID"); document.form2.mailid.focus(); return false; }} </script></head><body> <form name="form2" method="post" onsubmit="return validat()"> <tr> <td> Email-ID:</td> <td><input type="text" name="mailid"></td> </tr> <tr> <td></td> <td><input type="submit" name="sub" value="Submit"></td> </tr> </form> </body> </html>

PHONE NUMBER VALIDATION USING JAVASCRIPT

File name : index.php

<html>
<head>
<script type="text/javascript">
function validation()
{
var a = document.form.phone.value;
if(a=="")
{
alert("Please Enter Your Phone Number");
document.form.phone.focus();
return false;
}
}
</script>
</head>
<body>
<form name="form" method="post" onsubmit="return validation()">
<tr>
<td> Phone:</td>
<td><input type="text" name="phone""></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="sub" value="Submit"></td>
</tr>
</form>
</body>
</html>

RADIO BUTTON VALIDATION USING JAVASCRIPT

File name : index.php

<html>
<head>
<script LANGUAGE="JavaScript">
function ValidateForm(form){
ErrorText= "";
if ( ( form.gender[0].checked == false ) && ( form.gender[1].checked == false ) )
{
alert ( "Please choose your Gender: Male or Female" );
return false;
}
if (ErrorText= "") { form.submit() }
}
</script>
</head>
<body>
<form name="feedback" action="#" method=post>
Your Gender: <input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female
<input type="button" name="SubmitButton" value="Submit" onClick="ValidateForm(this.form)">
<input type="reset" value="Reset">
</form>
</body>
</html>

File name : index.php

<html>
<head>
<script type="text/javascript">
function checkButton(){
if(document.form1.button1.checked == true){
alert("Box1 is checked");
} else if(document.form1.button2.checked == true){
alert("Box 2 is checked");
}
}
</script>
</head>
<body>
<form name="form1">
<input type="radio" name=button1>Box 1
<br> <input type="radio" name=button2 CHECKED>Box 2
<br> <INPUT type="button" value="Get Checked" onClick='checkButton()'>
</form>
</body>
</html>

File name : index.php

<html>
<head>
<script type="text/javascript">
function evalGroup()
{
var group = document.radioForm.myRadio;
for (var i=0; i<group.length; i++) {
if (group[i].checked)
break;
}
if (i==group.length)
return alert("No radio button is checked");
alert("Radio Button " + (i+1) + " is checked.");
}
</script>
</head>
<body>
<form name="radioForm">
Radio Button 1: <input type="radio" name="myRadio" /><br />
Radio Button 2: <input type="radio" name="myRadio" /><br />
Radio Button 3: <input type="radio" name="myRadio" /><br />
Radio Button 4: <input type="radio" name="myRadio" /><br /><br />
<input type="button" value="Eval Group" onclick="evalGroup()" />
</form>
</body>
</html>

CHECKBOX VALIDATION USING JAVASCRIPT

File name : index.php

<html>
<head>
<script LANGUAGE="JavaScript">
function ValidateForm(form){
ErrorText= "";
if ( ( form.gender[0].checked == false ) && ( form.gender[1].checked == false ) )
{
alert ( "Please choose your Gender: Male or Female" );
return false;
}
if (ErrorText= "") { form.submit() }
}
</script>
</head>
<body>
<form name="feedback" action="#" method=post>
Your Gender: <input type="radio" name="gender" value="Male"> Male
<input type="checkbox" name="gender" value="Female"> Female
<input type="checkbox" name="SubmitButton" value="Submit" onClick="ValidateForm(this.form)">
<input type="reset" value="Reset">
</form>
</body>
</html>

File name : index.php

<html>
<head>
<script type="text/javascript">
function checkButton(){
if(document.form1.button1.checked == true){
alert("Box1 is checked");
} else if(document.form1.button2.checked == true){
alert("Box 2 is checked");
}
}
</script>
</head>
<body>
<form name="form1">
<input type="chechbox" name=button1>Box 1
<br> <input type="chechbox" name=button2 CHECKED>Box 2
<br> <INPUT type="button" value="Get Checked" onClick='checkButton()'>
</form>
</body>
</html>

File name : index.php

<html>
<head>
<script type="text/javascript">
function evalGroup()
{
var group = document.radioForm.myRadio;
for (var i=0; i<group.length; i++) {
if (group[i].checked)
break;
}
if (i==group.length)
return alert("No Checkbox is checked");
alert("Radio Button " + (i+1) + " is checked.");
}
</script>
</head>
<body>
<form name="radioForm">
Checkbox 1: <input type="chechbox" name="myRadio" /><br />
Chechbox 2: <input type="chechbox" name="myRadio" /><br />
Chechbox 3: <input type="chechbox" name="myRadio" /><br />
Chechbox 4: <input type="chechbox" name="myRadio" /><br /><br />
<input type="button" value="Eval Group" onclick="evalGroup()" />
</form>
</body>
</html>

SELECT INDEX VALIDATION USING JAVASCRIPT

File name : index.php

<html>
<head>
<script LANGUAGE="JavaScript">
function validation()
{
if(document.login.type.selectedIndex==0)
{ alert("Please select your member type");
document.login.type.focus();
return false;
}
return true;
}
</script>
</head>
<body>
<form name="login" method="post" action="#" onsubmit="return validation();">
<select name="type" class="texta1">
<option name="sel" value="Selected">Select Type</option>
<option name="fr" value="Freshers">Freshers</option>
<option name="ex" value="Experienced">Experienced</option>
<option name="un" value="Under_Studying">Under_Studying</option>
</select>
</form>
</body>
</html>

password validation

File name : index.php

<html>
<head>
<script type="text/javascript">
function validation()
{
var a = document.form.pass.value;
if(a=="")
{
alert("Please Enter Your Password");
document.form.pass.focus();
return false;
}
if ((a.length < 4) || (a.length > 8))
{
alert("Your Password must be 4 to 8 Character");
document.form.pass.select();
return false;
}
}
</script>
</head>
<body>
<form name="form" method="post" onsubmit="return validation()">
<tr>
<td> Passsword:</td>
<td><input type="password" name="pass""></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="sub" value="Submit"></td>
</tr>
</form>
</body>
</html>

File name : index.php

The html code for the buttons:

<input type="radio" name="retailStores" value="yes" style="margin-bottom:-1px;"/> Yes
<input type="radio" name="retailStores" value="no" style="margin-bottom:-1px;"/>

and the validation.js file has the following:


if ( (strRetailStores[0].checked == false ) && (strRetailStores[1].checked == false ) )
{
alert ( "Please choose Retail: Yes/No" );
document.frmSubscription.retailStores.focus();
valid = false;
}

File name : index.php

Validating radio buttons
After the contact_name text box has been checked, the gender radio buttons are validated:


if ( ( document.contact_form.gender[0].checked == false )
&& ( document.contact_form.gender[1].checked == false ) )
{
alert ( "Please choose your Gender: Male or Female" );
valid = false;
}

Mobile Number Validation

File Name:- index.php

<html> <head> <script type="text/javascript"> function Validation() { var a = document.form.phone.value; if(a=="") { alert("please Enter the Contact Number"); document.form.phone.focus(); return false; } if(isNaN(a)) { alert("Enter the valid Mobile Number(Like : 9566137117)"); document.form.phone.focus(); return false; } } </script> </head>
<body> <form name="form" method="post" onsubmit="return Validation()"> <tr> <td> Mobile No:</td> <td><input type="text" name="phone""></td> </tr> <tr> <td></td> <td><input type="submit" name="sub" value="Submit"></td> </tr> </form> </body> </html>









<script type="text/javascript"> function Validation() { var a = document.form.phone.value; if(a=="") { alert("please Enter the Contact Number"); document.form.phone.focus(); return false; } if(isNaN(a)) { alert("Enter the valid Mobile Number(Like : 9566137117)"); document.form.phone.focus(); return false; } if((a.length < 1) || (a.length > 10)) { alert(" Your Mobile Number must be 1 to 10 Integers"); document.form.phone.select(); return false; } } </script>


Text Area Validation

File Name:- index.php

<html> <head> <script type="text/javascript"> function Validation() { var a = document.form.address.value; if(a=="") { alert("please Enter the details"); document.form.address.focus(); return false; } if((a.length < 20) || (a.length > 100)) { alert(" Your textarea must be 20 to 100 characters"); document.form.address.select(); return false; } } </script> </head> <body> <form name="form" method="post" onsubmit="return Validation()"> <tr> <td> Address:</td> <td><textarea name="address" cols="60" rows="10"></textarea></td> </tr> <tr> <td></td> <td><input type="submit" name="sub" value="Submit"></td> </tr> </form> </body> </html>


Radiobutton Validation

File Name:- index.php

<html> <head> <script LANGUAGE="JavaScript"> function ValidateForm(form){ ErrorText= ""; if ( ( form.gender[0].checked == false ) && ( form.gender[1].checked == false ) )  { alert ( "Please choose your Gender: Male or Female" );  return false; } if (ErrorText= "") { form.submit() } } </script> </head> <body> <form name="feedback" action="#" method=post> Your Gender: <input type="radio" name="gender" value="Male"> Male <input type="radio" name="gender" value="Female"> Female <input type="button" name="SubmitButton" value="Submit" onClick="ValidateForm(this.form)"> <input type="reset" value="Reset"> </form>  </body> </html>


File Name:- index.php

<html> <head> <script type="text/javascript"> function checkButton(){ if(document.form1.button1.checked == true){ alert("Box1 is checked"); } else if(document.form1.button2.checked == true){ alert("Box 2 is checked"); } } </script> </head> <body> <form name="form1"> <input type="radio" name=button1>Box 1 <br> <input type="radio" name=button2 CHECKED>Box 2 <br> <INPUT type="button" value="Get Checked" onClick='checkButton()'> </form> </body> </html>


File Name:- index.php

<html> <head> <script type="text/javascript"> function evalGroup() { var group = document.radioForm.myRadio; for (var i=0; i<group.length; i++) { if (group[i].checked) break; } if (i==group.length) return alert("No radio button is checked"); alert("Radio Button " + (i+1) + " is checked."); } </script> </head> <body> <form name="radioForm"> Radio Button 1: <input type="radio" name="myRadio" /><br /> Radio Button 2: <input type="radio" name="myRadio" /><br /> Radio Button 3: <input type="radio" name="myRadio" /><br /> Radio Button 4: <input type="radio" name="myRadio" /><br /><br /> <input type="button" value="Eval Group" onclick="evalGroup()" /> </form> </body> </html>


Checkbox Validation

File Name:- index.php

<html> <head> <script LANGUAGE="JavaScript"> function ValidateForm(form){ ErrorText= ""; if ( ( form.gender[0].checked == false ) && ( form.gender[1].checked == false ) )  { alert ( "Please choose your Gender: Male or Female" );  return false; } if (ErrorText= "") { form.submit() } } </script> </head> <body> <form name="feedback" action="#" method=post> Your Gender: <input type="radio" name="gender" value="Male"> Male <input type="checkbox" name="gender" value="Female"> Female <input type="checkbox" name="SubmitButton" value="Submit" onClick="ValidateForm(this.form)"> <input type="reset" value="Reset"> </form>  </body> </html>


File Name:- index.php

<html> <head> <script type="text/javascript"> function checkButton(){ if(document.form1.button1.checked == true){ alert("Box1 is checked"); } else if(document.form1.button2.checked == true){ alert("Box 2 is checked"); } } </script> </head> <body> <form name="form1"> <input type="chechbox" name=button1>Box 1 <br> <input type="chechbox" name=button2 CHECKED>Box 2 <br> <INPUT type="button" value="Get Checked" onClick='checkButton()'> </form> </body> </html>


Select / combobox Validation

File Name:- index.php

<html> <head> <script LANGUAGE="JavaScript"> function validation() { if(document.login.type.selectedIndex==0) { alert("Please select your member type"); document.login.type.focus(); return false; } return true; } </script> </head>
<body> <form name="login" method="post" action="#" onsubmit="return validation();"> <select name="type" class="texta1"> <option name="sel" value="Selected">Select Type</option> <option name="fr" value="Freshers">Freshers</option> <option name="ex" value="Experienced">Experienced</option> <option name="un" value="Under_Studying">Under_Studying</option> </select> </form>  </body> </html>


Javascript Form validation

File name : index.php

<form method="post" action="step2.php" id="submitForm">


<label>Select Your State</label>
<select name="state" class="state" id="state">
<option value="0">-------Select State-------</option>
<option value="1">Andaman and Nicobar Islands</option><option value="2">Andhra Pradesh</option><option value="3">Arunachal Pradesh</option><option value="4">Assam</option><option value="5">Bihar</option><option value="6">Chandigarh</option><option value="7">Chhattisgarh</option><option value="8">Dadra and Nagar Haveli</option><option value="9">Daman and Diu</option><option value="10">Delhi</option><option value="11">Goa</option><option value="12">Gujarat</option><option value="13">Haryana</option><option value="14">Himachal Pradesh</option><option value="15">Jammu and Kashmir</option><option value="16">Jharkhand</option><option value="17">Karnataka</option><option value="18">Kenmore</option><option value="19">Kerala</option><option value="20">Lakshadweep</option><option value="21">Madhya Pradesh</option><option value="22">Maharashtra</option><option value="23">Manipur</option><option value="24">Meghalaya</option><option value="25">Mizoram</option><option value="26">Nagaland</option><option value="27">Narora</option><option value="28">Natwar</option><option value="29">Odisha</option><option value="30">Paschim Medinipur</option><option value="31">Pondicherry</option><option value="32">Punjab</option><option value="33">Rajasthan</option><option value="34">Sikkim</option><option value="35">Tamil Nadu</option><option value="36">Telangana</option><option value="37">Tripura</option><option value="38">Uttar Pradesh</option><option value="39">Uttarakhand</option><option value="40">Vaishali</option><option value="41">West Bengal</option> </select>
<span class="error" id="errorState"></span>

<label>Mobile No.</label>
<input name="mobile" class="textbox1" type="number" id="mobile" maxlength="10" placeholder="Enter Your Mobile Number"
required>
<span class="error" id="errorMobile"></span>

<label>Email</label>
<input name="email" class="textbox1" id="email" type="email" placeholder="Enter Your Email"
required>
<span class="error" id="errorEmail"></span>






<input class="button" type="submit" value="STEP 2">






</form>
</div>


script src="../ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<script>
$(function(){

$('document').on('click','#submitFrm',function(event){
event.preventDefault()
var validFlag = true;
var state = $('#state option:selected').val();
var mobile = $.trim($('#mobile').val());
var email = $.trim($('#email').val());
if (email=="")
{
$('#errorEmail').text("Email is required");
$('#email').val("");
validFlag = false;
}
else if (!email.match(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/))
{
$('#errorEmail').text("You have provided an invalid email");
$('#email').val("");
validFlag = false;
}
else
{
$('#errorEmail').text("");
}
if (!mobile.match(/^\d+$/))
{
$('#errorMobile').text("Mobile is required");
$('#mobile').val("");
validFlag = false;
}
else if (mobile.length != 10)
{
$('#errorMobile').text("You have provided an invalid mobile");
$('#mobile').val("");
validFlag = false;
}
else
{
$('#errorMobile').text("");
}
if(state == "0")
{
$('#errorState').text("State is required");
validFlag = false;
}
else
{
$('#errorState').text("");
}
if(validFlag){
$("#submitForm").submit();
}
});
});
</script>

Application Form Validation

File name : index.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Form validation</title>
<link rel="stylesheet" href="/examples/css/form-style.css">
<script>
// Defining a function to display error message
function printError(elemId, hintMsg) {
document.getElementById(elemId).innerHTML = hintMsg;
}

// Defining a function to validate form
function validateForm() {
// Retrieving the values of form elements
var name = document.contactForm.name.value;
var email = document.contactForm.email.value;
var mobile = document.contactForm.mobile.value;
var country = document.contactForm.country.value;
var gender = document.contactForm.gender.value;
var hobbies = [];
var checkboxes = document.getElementsByName("hobbies[]");
for(var i=0; i < checkboxes.length; i++) {
if(checkboxes[i].checked) {
// Populate hobbies array with selected values
hobbies.push(checkboxes[i].value);
}
}

// Defining error variables with a default value
var nameErr = emailErr = mobileErr = countryErr = genderErr = true;

// Validate name
if(name == "") {
printError("nameErr", "Please enter your name");
} else {
var regex = /^[a-zA-Z\s]+$/;
if(regex.test(name) === false) {
printError("nameErr", "Please enter a valid name");
} else {
printError("nameErr", "");
nameErr = false;
}
}

// Validate email address
if(email == "") {
printError("emailErr", "Please enter your email address");
} else {
// Regular expression for basic email validation
var regex = /^\S+@\S+\.\S+$/;
if(regex.test(email) === false) {
printError("emailErr", "Please enter a valid email address");
} else{
printError("emailErr", "");
emailErr = false;
}
}

// Validate mobile number
if(mobile == "") {
printError("mobileErr", "Please enter your mobile number");
} else {
var regex = /^[1-9]\d{9}$/;
if(regex.test(mobile) === false) {
printError("mobileErr", "Please enter a valid 10 digit mobile number");
} else{
printError("mobileErr", "");
mobileErr = false;
}
}

// Validate country
if(country == "Select") {
printError("countryErr", "Please select your country");
} else {
printError("countryErr", "");
countryErr = false;
}

// Validate gender
if(gender == "") {
printError("genderErr", "Please select your gender");
} else {
printError("genderErr", "");
genderErr = false;
}

// Prevent the form from being submitted if there are any errors
if((nameErr || emailErr || mobileErr || countryErr || genderErr) == true) {
return false;
} else {
// Creating a string from input data for preview
var dataPreview = "You've entered the following details: \n" +
"Full Name: " + name + "\n" +
"Email Address: " + email + "\n" +
"Mobile Number: " + mobile + "\n" +
"Country: " + country + "\n" +
"Gender: " + gender + "\n";
if(hobbies.length) {
dataPreview += "Hobbies: " + hobbies.join(", ");
}
// Display input data in a dialog box before submitting the form
alert(dataPreview);
}
};
</script>
</head>
<body>
<form name="contactForm" onsubmit="return validateForm()" action="/examples/actions/confirmation.php" method="post">
<h2>Application Form</h2>
<div class="row">
<label>Full Name</label>
<input type="text" name="name">
<div class="error" id="nameErr"></div>
</div>
<div class="row">
<label>Email Address</label>
<input type="text" name="email">
<div class="error" id="emailErr"></div>
</div>
<div class="row">
<label>Mobile Number</label>
<input type="text" name="mobile" maxlength="10">
<div class="error" id="mobileErr"></div>
</div>
<div class="row">
<label>Country</label>
<select name="country">
<option>Select</option>
<option>Australia</option>
<option>India</option>
<option>United States</option>
<option>United Kingdom</option>
</select>
<div class="error" id="countryErr"></div>
</div>
<div class="row">
<label>Gender</label>
<div class="form-inline">
<label><input type="radio" name="gender" value="male"> Male</label>
<label><input type="radio" name="gender" value="female"> Female</label>
</div>
<div class="error" id="genderErr"></div>
</div>
<div class="row">
<label>Hobbies <i>(Optional)</i></label>
<div class="form-inline">
<label><input type="checkbox" name="hobbies[]" value="sports"> Sports</label>
<label><input type="checkbox" name="hobbies[]" value="movies"> Movies</label>
<label><input type="checkbox" name="hobbies[]" value="music"> Music</label>
</div>
</div>
<div class="row">
<input type="submit" value="Submit">
</div>
</form>
</body>
</html>

File name : index.php

JavaScript Form validation

Application Form


JavaScript Innerhtml Form Validations.

File Name:- index.php

<!DOCTYPE html>
<html>
<body>

<p>Enter a number and click OK:</p>

<input id="id1" type="number" min="10" max="100">
<button onclick="myFunction()">OK</button>

<p>If the number is less than 10 or greater than 100, an error message will be displayed.</p>

<p id="demo"></p>

<script>
function myFunction() {
var inpObj = document.getElementById("id1");
if (inpObj.checkValidity() == false) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
} else {
document.getElementById("demo").innerHTML = "Input OK";
}
}
</script>

</body>
</html>


Range Overflow Validations.

File Name:- index.php

<p>Enter a number and click OK:</p>

<input id="id1" type="number" max="100">
<button onclick="myFunction()">OK</button>

<p>If the number is greater than 100 (the input's max attribute), an error message will be displayed.</p>

<p id="demo"></p>

<script>
function myFunction() {
var txt = "";
if (document.getElementById("id1").validity.rangeOverflow) {
txt = "Value too large";
} else {
txt = "Input OK";
}
document.getElementById("demo").innerHTML = txt;
}
</script>


Range underflow Validations.

File Name : index.php

<p>Enter a number and click OK:</p>

<input id="id1" type="number" min="100">
<button onclick="myFunction()">OK</button>

<p>If the number is less than 100 (the input's min attribute), an error message will be displayed.</p>

<p id="demo"></p>

<script>
function myFunction() {
var txt = "";
if (document.getElementById("id1").validity.rangeUnderflow) {
txt = "Value too small";
} else {
txt = "Input OK";
}
document.getElementById("demo").innerHTML = txt;
}
</script>

Inner Html Form JsValidations.

File Name : index.php

<html > <head> <!--validation--> <script typ="text/javascript" src="innerHTMLValidation.js" ></script>
</head>
<body>
<div class="container"> <div class="content"> <center> <form name="form1" method="post" action="success.html"> <fieldset>
<h1>Demo Registration Form</h1>
<table border='0'> <tr> <td><LABEL for="firstname">First Name:<sup style="color:#F00">*</sup> </LABEL></td>
<td><INPUT type="text" id="firstname"></td><td width="200px"><i style="color:red;" id="pointfn"></i></td> </tr>
<tr> <td>
<LABEL for="lastname">Last Name:<sup style="color:#F00">*</sup> </LABEL></td>
<td><INPUT type="text" id="lastname"></td><td width="200px"><i style="color:red;" id="pointln"></i></td> </tr>
<tr> <td><LABEL for="gender">Gender:<sup style="color:#F00">*</sup> </LABEL></td>
<td><INPUT type="radio" name="gender" value="Male"> Male <INPUT type="radio" name="gender" value="Female"> Female</td>
<td width="200px"> <i style="color:red;" id="pointgendr"></i></td> </tr>
<tr> <td><LABEL for="dob">Date of Birth:<sup style="color:#F00">*</sup> </LABEL></td>
<td> <select id="dd">
<option value="dd">DD</option>
<script type="text/javascript">
for(var i=1;i<32;i++)
document.write("<option value='"+i+"'>" + i+"</option> "); </script>
</select>
</select>
<select id="mmm"> <option value="mmm">MMM</option> <option value="0">JAN</option> <option value="1">FEB</option> <option value="2">MAR </option> <option value="3">APR</option> <option value="4">MAY</option> <option value="5">JUN</option> <option value="6">JUL</option> <option value="7">AUG</option> <option value="8">SEP</option> <option value="9">OCT</option> <option value="10">Nov</option> <option value="11">DEC</option> </select>
<select id="yyyy">
<option value="yyyy"selected>YYYY</option>
<script type="text/javascript">
var dt= new Date();
for(var i=1979;i<=dt.getFullYear()-18;i++) document.write("<option value='"+i+"'>" + i+"</option> "); </script> </select> </td>
<td width="200px"><i style="color:red;" id="pointdob"></i> </td> </tr>
<tr> <td><LABEL for="address" style="text-align:left;">Address:<sup style="color:#F00">*</sup> </LABEL></td>
<td><textarea id="address" name="address" rows="4" cols="20"></textarea></td>
<td width="200px"><i style="color:red;" id="pointadrs"></i> </td> </tr>
<tr> <td><LABEL for="contctno">Contact Number:<sup style="color:#F00">*</sup> </LABEL></td>
<td><INPUT type="text" id="contctno"></td>
<td width="200px"><i style="color:red;" id="pointcontct"></i></td> </tr>
<tr> <td><LABEL for="email">Email:<sup style="color:red;">*</sup> </LABEL></td>
<td><INPUT type="text" id="email"></td>
<td width="200px"><i style="color:red;" id="pointemail"></i></td> </tr>
<tr> <td></td><td><br/><INPUT type="submit" onClick="return validateForm()" value="Submit"> <INPUT type="reset" onClick="return confirmreset()"></td> </tr>
<tr> <td></td>
<td style="font-size:12px;text-align:right;"><br/><i style="color:red;font-size:12px;align:right;" >* - Mandatory</i></td> </tr> </table>
<fieldset> </FORM></center> </div> </div>
</body> </html>

innerHTMLValidation.js

File Name : innerHTMLValidation.js

var namepattern=/^[a-zA-Z]+$/ var phonepattern = /^\d{10}$/ var emailpattern =/^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z0-9_]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.([a-zA-Z]{2,4})$/ var emailpattern2 =/^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z0-9_]+)*$/ var idpattern=/^\d{6}$/;
function validateForm()
{
var x=document.forms["form1"]["firstname"];
if (x.value=="") { document.getElementById('pointfn').innerHTML="Please enter the first name.";
x.focus();
return false;
}
else if(x.value.length>20)
{
x.value=""; document.getElementById('pointfn').innerHTML="Please enter less than 20 characters.";
x.focus(); return false;
}
else if ((!namepattern.test(x.value)))
{ document.getElementById('pointfn').innerHTML="Please enter only alphabets.";
x.value="";
x.focus();
return false;
}
document.getElementById('pointfn').innerHTML=''; x=document.forms["form1"]["lastname"];
if(x.value=="") { document.getElementById('pointln').innerHTML="Please enter the Last name.";
x.focus(); return false; }
else if(x.value.length>20)
{
x.value=""; document.getElementById('pointln').innerHTML="Please enter less than 20 characters.";
x.focus();
return false;
}
else if (!namepattern.test(x.value))
{
x.value=""; document.getElementById('pointln').innerHTML="Please enter only alphabets.";
x.focus();
return false;
}
document.getElementById('pointln').innerHTML=""; if((document.form1.gender[0].checked==false)&&(document.form1.gender[1].checked==false))
{
document.form1.gender[0].focus(); document.getElementById('pointgendr').innerHTML='Please select a gender.'; return false;
}
document.getElementById('pointgendr').innerHTML='';
var dd=document.form1.dd.value;
var mmm=document.form1.mmm.value;
var yyyy=document.form1.yyyy.value;
if(!validdate(dd,mmm,yyyy))
{ document.getElementById('pointdob').innerHTML="Plaese select a valid date.";
return false;
}
document.getElementById('pointdob').innerHTML="";
x= document.getElementById("address");
if(x.value==null || x.value=="" )
{
x.value=""; document.getElementById('pointadrs').innerHTML="Please enter the address.";
x.focus(); return false;
}
else if(x.value.length<20) {
x.value=""; document.getElementById('pointadrs').innerHTML="Please enter atleast 20 characters.";
x.focus();
return false;
}
document.getElementById('pointadrs').innerHTML=""; x=document.form1.contctno;
if(x.value=="")
{
x.value=""; document.getElementById('pointcontct').innerHTML="Please enter the contact number.";
x.focus();
return false;
}
else if(isNaN(x.value))
{
x.value=""; document.getElementById('pointcontct').innerHTML="Please enter only digits.";
x.focus(); return false;
}
else if(x.value.length!=10)
{
x.value=""; document.getElementById('pointcontct').innerHTML="Please enter only 10 digits.(Mobile number)";
x.focus(); return false;
}
else if(!phonepattern.test(x.value))
{
x.value=""; document.getElementById('pointcontct').innerHTML="Please enter a valid contact number.";
x.focus();
return false;
}
document.getElementById('pointcontct').innerHTML=""; x=document.form1.email;
if(x.value=="")
{
x.value=""; document.getElementById('pointemail').innerHTML="Please enter the email id.";
x.focus(); return false; } else if(!emailpattern.test(x.value)) {
x.value=""; document.getElementById('pointemail').innerHTML="Please enter a valid email address.";
x.focus();
return false;
}
document.getElementById('pointemail').innerHTML=""; return confirm("Do you want to submit the form?");
}
function validdate(dd,mm,yyyy)
{
var dateobj = new Date(yyyy, mm, dd);
var datecurrent= new Date(); if((dateobj.getMonth()!=mm)||(dateobj.getDate()!=dd)||(dateobj.getFullYear()!=yyyy)||(dateobj>datecurrent))
{
return false;
}
return true;
}
function confirmreset()
{
if(confirm("Do you want to reset the form?"))
{
document.getElementById('pointfn').innerHTML=""; document.getElementById('pointln').innerHTML=""; document.getElementById('pointgendr').innerHTML=""; document.getElementById('pointdob').innerHTML=""; document.getElementById('pointadrs').innerHTML=""; document.getElementById('pointcontct').innerHTML=""; document.getElementById('pointemail').innerHTML=""; return true;
}
else return false;
}



javascript inline validation Form Validations.

File Name : index.php

<html>
<head>
<meta charset="utf-8">
<title>Validation using JavaScript</title>
<script type="text/javascript">

var hasFocus = false;

function checkName(form)
{
var eobj=document.getElementById('realnameerror');
var sRealName = form.realname.value;
var oRE = /^[a-z0-9]+[_.-]?[a-z0-9]+$/i;
var error=false;
eobj.innerHTML='';
if (sRealName == '') {
error='Error: Username cannot be blank!';
}
else if (sRealName.length < 4)
{
error="UserName should be atleast 4 characters long";
}
else if (!oRE.test(sRealName))
{
error="Incorrect format.";
}
if (error)
{
if (hasFocus == false) {
form.realname.focus();
hasFocus = true;
}
eobj.innerHTML=error;
return false;
}
return true;
}

function checkEmail(form) /* for email validation */
{
var eobj=document.getElementById('emailerror');
eobj.innerHTML='';
var error = false;
if (form.email.value.length == 0) {
error = 'Please enter email.';
} else if (/^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$/.test(form.email.value))
{
return true;
} else {
error = 'Invalid E-mail Address! Please re-enter.';
}
if (error) {
eobj.innerHTML=error;
if (!hasFocus) {
form.email.focus();
hasFocus = true;
}
return false;
}

return true;
}

function validatePwd(form) /* password & retype-password verification */
{
var eobj1=document.getElementById('passworderror');
var eobj2=document.getElementById('password2error');
var minLength=6;
var invalid=' ';
var pw1=form.password.value;
var pw2=form.password2.value;
var error=false;
eobj1.innerHTML='';
eobj2.innerHTML='';
if (pw1.length<1)
{
error='Please enter your password.';
}
else if (pw1.length < minLength)
{
error='Your password must be at least ' + minLength + ' characters long. Try again.';
}
else if (pw1.indexOf(invalid) > -1)
{
error='Sorry, spaces are not allowed.';
} else if (pw2.length == 0) {
error='Please retype password.';
if (!hasFocus) {
form.password2.focus();
hasFocus = true;
}
eobj2.innerHTML=error;
return false;
}
if (error)
{
if (!hasFocus) {
form.password.focus();
hasFocus = true;
}
eobj1.innerHTML=error;
return false
}
if (pw1 != pw2)
{
eobj2.innerHTML=' passwords not matching.Please re-enter your password.';
if (!hasFocus) {
form.password2.focus();
hasFocus = true;
}
return false;
}
return true;
}

function validPhone(form) /* phone no validation */
{
var eobj=document.getElementById('phonenoerror');
var valid = '0123456789';
var phone = form.phoneno.value;
var error=false;
var i=0;
var temp;
eobj.innerHTML='';
if (phone == '')
{
error='This field is required. Please enter phone number';
}
else if (!phone.length > 1 || phone.length < 10)
{
error='Invalid phone number length! Please try again.';
}
else
{
for (i=0; i < phone.length; i++)
{
temp = '' + phone.substring(i, i + 1);
if (valid.indexOf(temp) == -1)
{
error='Invalid characters in your phone. Please try again.';
}
}
}
if (error)
{
if (!hasFocus) {
form.phoneno.focus();
hasFocus = true;
}
eobj.innerHTML=error;
return false;
}
return true;
}

function validate()
{
hasFocus = false;
var form = document.forms['form'];
var ary=[checkName,checkEmail,validatePwd,validPhone];
var rtn=true;
var z0=0;
for (var z0=0;z0<ary.length;z0++)
{
if (!ary[z0](form))
{
rtn=false;
}
}
return rtn;
}
</script>
</head>
<body>

<form action="" method="post" name="form" onsubmit="return validate()">
User Name : <input type="text" name="realname" size="19"><span id="realnameerror" ></span>
<br>
E-Mail : <input type="text" name="email" size="25"><span id="emailerror" ></span>
<br>
Password : <input type="password" name="password" maxlength="12" size="25"><span id="passworderror" ></span>
<br>
Retype password: <input type="password" name="password2" maxlength="12" size="25"><span id="password2error" ></span>
<br>
PhoneNo : <input type="phoneno" name="phoneno" maxlength="10" size="25"><span id="phonenoerror" ></span>
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Range underflow Validations.

File Name : index.php


Range underflow Validations.

File Name : index.php






Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here