Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML
MySQL
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments
Date validation in JSP
This example illustrates how to use date validation in a JSP page. Here in this code we are using JavaScript for validating date in a specified format as "MM/DD/YYYY".
 
 

Date validation in JSP

                         

Example for validating date in a specified format in a JSP page

This example illustrates how to use date validation in a JSP page. Here in this code we are using JavaScript for validating date in a specified format as "MM/DD/YYYY". We are using JavaScript for validating JSP at client side so that it will take less time in validation rather than having validation at server side.

We have created a JSP file "DateValidation.jsp", which is doing the whole working for us. If date is not inserted in a correct way then this will display error message using "alert()". Here in this example following numbers of validations are done:

  • The date format should be : MM/DD/YYYY
  • Month should be valid (i.e between 1 to 12)
  • Entered day should be a valid day (i.e between 1 to 31)
  • Please enter a valid 4 digit year between 1900 and 2500
  • For February month special validation is done(i.e if it is a leap year then day 29 is valid and if
    it is not a leap year then 29 days are not valid)
  • If at time of inserting month and day value "04" is written as "4" then it will automatically append
    "0" and then do validation in JavaScript
  • All characters must be numbers.

"DateValidation.jsp" is calling JavaScript's method "ValidateDate()" which is doing the two things. 

First, it is ensuring that input date field must not be empty. Second, date entered by user is valid. If it is not in a given format and according to checks then error message would be displayed and if it is accurate then it will display "Entered date is valid" in "alert()". Full code for "DateValidation.jsp" is given as below:

1. DateValidation.jsp

<%@ page language="java" %>
<html>
<head><title>Date Validation in JSP</title>
<script language = "Javascript">
var separator= "/";
var minYear=1900;
var maxYear=2500;

function isInteger(s){
var i;
for (i = 0; i < s.length; i++){ 
// Check that current character is a number or not.
var c = s.charAt(i);
if (((c < "0") || (c > "9"))) return false;
}
// All characters are numbers.
return true;
}

function stripCharsInBag(s, bag){
var i;
var returnString = "";
// Search through string's characters one by one.
// If character is not in bag, append to returnString.
for (i = 0; i < s.length; i++){ 
var c = s.charAt(i);
if (bag.indexOf(c) == -1) returnString += c;
}
return returnString;
}

function daysInFebruary (year){
// February has 29 days in any year evenly divisible by four,
// EXCEPT for centurial years which are not also divisible by 400.
return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
for (var i = 1; i <= n; i++) {
this[i] = 31
if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
if (i==2) {this[i] = 29}

return this
}

function isDate(dtStr){
var daysInMonth = DaysArray(12)
var pos1=dtStr.indexOf(separator)
var pos2=dtStr.indexOf(separator,pos1+1)
var strMonth=dtStr.substring(0,pos1)
var strDay=dtStr.substring(pos1+1,pos2)
var strYear=dtStr.substring(pos2+1)
strYr=strYear
if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
for (var i = 1; i <= 3; i++) {
if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
}
month=parseInt(strMonth)
day=parseInt(strDay)
year=parseInt(strYr)
if (pos1==-1 || pos2==-1){
alert("The date format should be : MM/DD/YYYY")
return false
}
if (strMonth.length<1 || month<1 || month>12){
alert("Please enter a valid month")
return false
}
if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
alert("Please enter a valid day")
return false
}
if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
return false
}
if (dtStr.indexOf(separator,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, separator))==false){
alert("Please enter a valid date")
return false
}
alert("Entered date is valid")
return true
}

function ValidateDate(){
var dt=document.frm.txtDate
if (isDate(dt.value)==false){
dt.focus()
return false
}
return true
}
</script>
</head>
<body>
<form name="frm" method="post" onSubmit="return ValidateDate()">
<p>Enter any Date <font color="#CC0000"><b>(MM/DD/YYYY)</b></font> 

<input type="text" name="txtDate" maxlength="10" size="15">
</p>
<p> 
<input type="submit" name="Submit" value="Submit">
</p>
</form>
</body>
</html>

To run this example you have to simply create this "DateValidation.jsp" and run the web server you are using and type the URL "http://localhost:8080/JSPMultipleForms/DateValidation.jsp" in address bar . We have taken the example folder JSPMultipleForms as the application directory but you can take your own as you like.

Output:

If user doesn't enter date in a specified manner then it will show error message date format should be MM/DD/YYYY.

If user does not enter year between 1900 and 2500

If user does not insert a valid month

Since February is a month which is having 28 days in month if it is not a leap year and if it a leap year then user can insert '29' 

If entered value is in correct and specified format then it will display message "Entered date is valid"

Download Source Code

                         

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

1 comments so far (
post your own) View All Comments Latest 10 Comments:

very Good

Posted by harita on Thursday, 08.7.08 @ 14:54pm | #71566

Latest Tutorials:
J2ME Event Handling Ex
J2ME HashTable Example
J2ME Icon MIDlet Examp
J2ME Image Item Exampl
J2ME Image Example
J2ME Item State Listen
J2ME Key Codes Example
J2ME KeyEvent Example
J2ME Label Example
J2ME Random Number
J2ME Read File
J2ME RMS Sorting Examp
J2ME Timer MIDlet Exam
Custom Item in J2ME
Creational Design Patt
Design Patterns
Throwing Run time exce
Grid in Echo3
Creating Table in Echo
JPA Introduction
Java bigdecimal toBigI
Java bigdecimal shortV
Java bigdecimal shortV
Java bigdecimal signum
Java bigdecimal stripT
Java bigdecimal subtra
Java bigdecimal subtra
Java bigdecimal toBigI
Java bigdecimal toEngi
Java bigdecimal toPlai
Java bigdecimal toStri
Java bigdecimal ulp ex
Java bigdecimal unscal
Java bigdecimal valueO
Java bigdecimal valueO
Java bigdecimal valueO
Java bigdecimal setSca
Java bigdecimal setSca
Java bigdecimal scaleB
Java bigdecimal scale
Java bigdecimal round
Java bigdecimal remain
Java bigdecimal remain
Java bigdecimal precis
Java bigdecimal pow me
Java bigdecimal pow ex
Java bigdecimal plus m
Java bigdecimal plus e
Java bigdecimal negate
Java bigdecimal negate
Java bigdecimal multip
Java bigdecimal multip
Java BigDecimal movePo
Java bigdecimal movePo
Java bigdecimal min ex
Java bigdecimal max ex
CheckBox component in
Visibility of Componen
Loading delay componen
Simple input applicati
Opening a new window i
Hello World in Echo3 f
Use of Local Inner cla
JSP bean set property
Java Method Synchroniz
Java Method Return Val
JAVA Method Wait
JDBC vs ORM
Java BigDecimal divide
Java BigDecimal divide
Java BigDecimal divide
Java BigDecimal divide
Java BigDecimal divide
Java BigDecimal double
Java BigDecimal equals
Java BigDecimal hashCo
Java BigDecimal intVal
Java BigDecimal intVal
Java BigDecimal longVa
Java BigDecimal longVa
Java BigDecimal abs ex
Java BigDecimal add ex
Java BigDecimal byteVa
Java Bigdecimal class
Java BigInteger long
Java BigDecimal compar
Java divide method exa
Java BigDecimal floatV
Appending Image into t
J2ME Convert Date To S
Appending string in J2
J2ME Enumeration Examp
J2ME Display Size Exam
J2ME Current Date And
J2ME Form Class
Creating Dynamic Tree
Introduction to RCFace
JSP bean get property
Java bean example in J
J2ME Record Store Exam
Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.