I'm using Struts2 JQuery datepicker tag.
But I'm not able to validate it. In my validation.xml
file, i am taking it as date
, but it removes the time part. Any solution to it? Should i use regex to validate my date time?
JSP Form
code is somewhat same as it was is in my earlier question Struts2 jquery datepicker passing 0 or null value to action class
Action class:
public Date getDateAndTimeOfOccurance() {
return dateAndTimeOfOccurance;
}
public void setDateAndTimeOfOccurance(Date dateAndTimeOfOccurance) {
System.out.println(dateAndTimeOfOccurance);
this.dateAndTimeOfOccurance = dateAndTimeOfOccurance;
}
public String execute() throws Exception {
.
.
ps.setTimestamp(13, new java.sql.Timestamp(getDateAndTimeOfOccurance().getTime()));
/* i have modified my database because the time values in java.sql.Date have been depreciated */
.
.
}
is there any existing solution for it? Should i use regex
validator?
UPDATE
For experiment, I removed the validation part but the time received in the action is still 00:00:00
.
UPDATE 2
i found a way to solve this problem by recieving as mentioned in comments of of this question Struts2 JQuery Datepicker not working properly. Also i have dropped validation.xml. Now i'm using annotation. Now the problem is how to validate it? should it be a regex
or is there a struts validation way of validating a string as a date (like using validate()
method, i'm not sure is it a good practice).
UPDATED Code (with update 2)
Action class
@RequiredStringValidator(message = "Please enter the date and time of occurance")
public String getDateAndTimeOfOccurance() {
return dateAndTimeOfOccurance;
}
public void setDateAndTimeOfOccurance(String dateAndTimeOfOccurance) {
this.dateAndTimeOfOccurance = dateAndTimeOfOccurance;
}
public void execute(){
....
Date d = null;
try {
d = new SimpleDateFormat("dd-MMM-yyyy hh:mm", Locale.getDefault()).parse(getDateAndTimeOfOccurance());
} catch (java.text.ParseException e) {
e.printStackTrace();
addFieldError(dateAndTimeOfOccurance, "Please enter a valid date");
return INPUT;
}
Timestamp t = new java.sql.Timestamp(d.getTime());
ps.setTimestamp(13, t);
...
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…