I have a date input box in my lift application, and I want to check that a user-entered date is in correct format: dd/mm/yyyy.
How can I write a reg
As user unknown has written you should use some library that knows how to handle dates correctly including days per specific month and leap years.
SimpleDateFormat
is not very intuitive regarding rollovers of fields and initially accepts wrong dates by just rolling over the other fields. To prevent it from doing so you have to invoke setLenient(false)
on it. Also keep in mind that SimpleDateFormat
is not thread-safe so you need to create a new instance every time you want to use it:
def validate(date: String) = try {
val df = new SimpleDateFormat("dd/MM/yyyy")
df.setLenient(false)
df.parse(date)
true
} catch {
case e: ParseException => false
}
Alternatively you may also use Joda Time which is a bit more intuitive than the Java Date APIs and offers thread-safe date formats:
val format = DateTimeFormat.forPattern("dd/MM/yyyy")
def validate(date: String) = try {
format.parseMillis(date)
true
}
catch {
case e: IllegalArgumentException => false
}