Java sample code
This code is used in the validation of the the date text field on the fields loss of focus. Rather than using a message box, the section of the date that is generating the error, is highlighted. Further validation is carried out prior to sending the date to the database. The second validation occurs when the getDate() method is called.
private boolean validation() throws Exception {
String date = this.getText();
//Check to see if a date has been entered
if (!(date.equals(new String("DD-MM-YYYY")))){
int day = Integer.parseInt(date.substring(0,2));
int month = Integer.parseInt(date.substring(3,5));
int year =Integer.parseInt(date.substring(6,8));
//Used to check if the entered year is a leap year
java.util.GregorianCalendar leapYear = new
java.util.GregorianCalendar();
//System.out.println(day);
//System.out.println(month);
//System.out.println(this.getText().length());
//Check weather a complete date has been entered
if (this.getText().length() != 10){
this.selectAll();
this.setSelectedTextColor(java.awt.Color.red);
return false;
}
//Check weather a valid # months has been entered
if (month >12){
this.select(3,5);
//Highlight month
this.setSelectedTextColor(java.awt.Color.red);
return false;
}//end if
//Check weather a valid # days has been entered for a given
month
switch (month){
case 1: case 3: case 5: case 7: case 8: case
10: case 12:
if (day > 31){
this.select(0,2);
this.setSelectedTextColor(java.awt.Color.red);
return false;
}
break;
case 2:
if(leapYear.isLeapYear(year)){
if(day > 29){
this.select(0,2);
this.setSelectedTextColor(java.awt.Color.red);
return false;
}//end
inner if
else if(day > 28){
this.select(0,2);
this.setSelectedTextColor(java.awt.Color.red);
return false;
}//end
else
}//end outer if
break;
default:
if (day >30){
this.select(0,2);
this.setSelectedTextColor(java.awt.Color.red);
return false;
}//end if
}//end switch
}//end text(DD-MM-YYYY) if
return true;
}