JavaScript Tutorials
- What is Javascript?
- What is BOM?
- What is DOM?
- Variable
- check variable value is empty
- JavaScript Output
- Functions
- Javascript Events
- Input Events
- onchange Event
- Javascript Output methods
- If else statement
- Arrays
- Pattern Validation
- Form Validation
- Inner Html Form Validation
- Inline Form Validation
- Checkbox Validation
- Inline Inner Html Form Validation
- Server side php Validation
- Validate a HTML Form with PHP
- window and window location
- Get Text Value
- Get hidden field value
- JavaScript & PHP
- Date Format
- get php value in javascript
- Redirect page & Autoredirect page
- Auto Refresh page & Div
- How to get select text value from Dropdown box
- How to clear browser history in javascript
- Checkbox Problems
- Select option problems
- Popup Contact Form
- Sidebar Contact Form
- How to use a multistep Form or Form wizard
- Auto Calculate Price
- print Application Form
- Auto Calculate GST in Javascript by select price
- Calculate GST by input value in text box Jquery
- Calculate Discount
- onClick Checkbox
- autofil form data click on checkbox
- Show subcategory list
- Show city list as per state
- Show district list as per country and state
- Show good morning good night wish
- image upload with preview image
- Print Div Content
- Show modal popup on page load
- filter table data usign javascript.
- Character Limit Validation.
- Validate File 5MB Upload
- Validate Special character
- More File Upload
- Call JavaScript Function After Page Load
- Drop Down First option Value Disabled --- Please Select ---
- How to Disable Submit Button After Form Submission
- How to disable browser back button using Jquery?
- How to Remove selected item from second & third dropdown list?
- Interview Questions of JavaScript.
Important Link
Home » Javascript »
About Javascript
Javascript Form Validations.
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