Reputation: 675
I'm adding validation for date options in a Scala form; there are optional date fields that allow a user to search between a specific date/time range, but the second date needs to be after the first date for a valid range.
At the moment this validation works:
val searchForm = Form(
mapping(
"ItemID" -> optional(text),
"fromDate" -> optional(jodaLocalDate("yyyy-MM-dd:HH:mm:ss")),
"toDate" -> optional(jodaLocalDate("yyyy-MM-dd:HH:mm:ss")),
"Class" -> optional(text),
"Status" -> optional(text),
"Group" -> optional(text),
"Area" -> nonEmptyText,
"Ordered" -> optional(text)
)(SearchModel.apply)(SearchModel.unapply)
verifying("Both or no dates must be selected. Date/Time range must be valid.", f => (f.fromDate.isEmpty && f.toDate.isEmpty)||
((f.fromDate.isDefined&&f.toDate.isDefined)&&f.fromDate.head.isBefore(f.toDate.head))))
But it only compares the dates and ignores the time section HH:mm:ss
.
Is there a way to add time validation too? Should I be using a different validation method?
Upvotes: 0
Views: 846
Reputation: 1179
As long as you get the time section from the form, the Date calling .before()
would definitely check on the time portion, too.
Try:
def validateDates(fromDate: Option[Date], toDate: Option[Date]): Boolean = {
if(fromDate.isEmpty || toDate.isEmpty) false
else fromDate.get.before(toDate.get)
}
Then:
verifying("Both or no dates must be selected. Date/Time range must be valid.", f => validateDates(f.fromDate, f.toDate))
Edit:
Just realised this wouldn't pass if both date fields are empty, so a slight modification to validateDates
would fix that:
def validateDates(fromDate: Option[Date], toDate: Option[Date]): Boolean = {
if(fromDate.isEmpty && toDate.isEmpty) true
else if(fromDate.isEmpty || toDate.isEmpty) false
else fromDate.get.before(toDate.get)
}
Upvotes: 1