FREE tutorial,solution,RSS Feeds on Operating Systems, Programming, Web Development, Applications, Databases, Networking, Hardware, Security, SEO Free Expertsforge Membership
Join us as Moderator
Submit Article to Expertsforge.com Submit Article My Expertsforge
 
RSS Feeds, Help Help RSS Feeds
bannertop
 

Java Tutorial: Java DateField Validation Source Code

gravikumar
9/3/2005 3:17:50 AM, Views: 2677
You can validate the textfield for the dateformat(mm/dd/yyyy) with this class module.

Procedure :

1. While declaring textfield in java-swings,(for ex:JTextField txtdate)instead of declaring like above,you can declare like: DateTextField txtdate.

2. Copy the following source code in a notepad and save as DateTextField.java in the location of your java file.

Usage :

You enter the date(for ex:08/25/2005(mm/dd/yyyy)).
if u just enter '08' automatically a '/' adds and after you type '25',automatically '/' addsup.

Then after u finish typing '2005',just press space bar or press any alphabet. It makes a validation on the entered date.

If it finds error,then it deletes the entered date.Then u can enter again the correct date.

Source Code : 'DateTextField.java'
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;

class DateTextField extends JTextField
{
   protected Document createDefaultModel()
   {
      return new DateDocument(this);
   }

   class DateDocument extends PlainDocument
   {
      JTextField textFld ;
      public DateDocument(JTextField xTextFld)
      {
         textFld = xTextFld;
      }

public void insertString(int offset, String str, AttributeSet a)
         throws BadLocationException
   {
      if(str == null || dateSatisfied(textFld.getText())){
         boolean validity = format(textFld.getText());
         if(validity == false)
         {
JOptionPane.showMessageDialog(null,"Invalid
Entry!!","Alert!",JOptionPane.INFORMATION_MESSAGE);
            textFld.setText(" ");
            
         }
         else
         return;
      }

      String dateStr       = "";
      char[] inpStr       = str.toCharArray();
      boolean digitAdded = false;
      boolean slashAdded = false;

      for(int i = 0; i < inpStr.length; i++)
      {
         if(Character.isDigit(inpStr[i]))
         {
            digitAdded = true;
            dateStr += String.valueOf(inpStr[i]);
         }
if(inpStr[i] == '/' && slashCountAt(textFld.getText(), 2, offset))
         {
            slashAdded = true;
            dateStr += String.valueOf(inpStr[i]);
         }
      }
      if(offset == 1 && slashAdded == false)
         dateStr += '/';
if(offset == 3 && digitAdded == true && slashCount(textFld.getText(),
1))
         dateStr += '/';
if(offset == 4 && slashAdded == false && slashCount(textFld.getText
(), 1))
         dateStr += '/';
      super.insertString(offset, dateStr, a);
   }

public boolean slashCountAt(String text, int count, int offset)
      {
         boolean matchCount = false;
         if(text != null && !text.equals(""))
         {
            String split[] = text.split("/");
            int splitCount = split.length-1;
            if(splitCount < count){
               if(text.charAt(offset-1) !
= '/')
                  matchCount = true;
         }
         else
               matchCount = false;
         }
         return matchCount;
      }

      public boolean slashCount(String text, int count)
      {
         boolean matchCount = false;
         if(text != null && !text.equals(""))
         {
            String split[] = text.split("/");
            int splitCount = split.length -1;
if(splitCount <= count && text.charAt(text.length()-1) != '/')
               matchCount = true;
         }
         return matchCount;
      }
   
      
         public boolean format(String value){

            try{

         int monthindex = value.indexOf("/");
         String month = value.substring(0,monthindex);
               int oldIndex = monthindex;

      int dateindex = value.indexOf("/",monthindex+1);

                        String date = value.substring(oldIndex+1,dateindex);
      String year = value.substring(dateindex+1);

      int monthid = Integer.parseInt(month);
      int idate = Integer.parseInt(date);
      int iyear = Integer.parseInt(year);
      int leapyear = Integer.parseInt(year) % 4;

      if( monthid<13 && monthid>0)
      if(idate<32 && idate>0)
      {
if((monthid == 2 || monthid == 4 || monthid == 6 || monthid == 9 ||
monthid == 11)&&(idate == 31) )
                     
   return false;
if(monthid ==2 && idate > 29)
return false;
if((monthid ==2) &&(idate == 29) && (leapyear!= 0))
                     
   return false;
if((Integer.parseInt(year) < 2010)   && (iyear > 0))
                     
   return true;
   else
                     
   return false;
   }
   else
   return false;
   else
   return false;
         }
            catch(NullPointerException e)
            {
               return false;
            }
            catch(NumberFormatException e)
            {
               return false;
            }
            catch(Exception e)
            {
               return false;
            }
         }

         
      public boolean dateSatisfied(String text)
      {
         boolean satisfy = false;
         if(text != null && !text.equals(""))
         {
            String split[] = text.split("/");
            int splitCount = split.length -1;
            if(splitCount == 2)
            {
      int slashPos = text.lastIndexOf("/") +1;
      int yearLen    = text.length() - slashPos;
               if(yearLen == 4)
               {
                  satisfy = true;
               }
            }
            
         }
         return satisfy;
      }//end of dissatisfied
   }
}   
Next Steps:
Add this Tutorial to:
Blink Blink del.icio.ous Del.icio.us Digg Digg
Fark Fark Furl Furl Google Google
Reddit Reddit Simpy Simpy Spurl Spurl
Technorati Technorati Windows Live Win Live Yahoo Yahoo
Rate Me!
Avg Visitor Rating: Average Visitor Rating is 1 out of 5
Number of Ratings : 1 Votes
Rate:
Send Private MessageSend Message
Signup / Login To View the Solution or Provide Comments
Post Comment/Solution
Comment:*
        (Link Rules) 
  Use : [bold] for <b>; [/bold] for </b>; [italic] for <i>; [/italic] for </i>; [code] & [/code] for code
 
Categories
Options
Java RSS Feed
gravikumar
Most Popular Tutorial
Most Popular Solution
Top Rated
Top Rankers
Overall
1. jawahar (250)
2. gravikumar (200)
Yearly -2008
No Rankings!
Expertsforge Sponsors
bnrtop