I'm trying to create a custom date validator. My goal is to store the dates in the database as a standard date but display and validate the dates on the front end in a custom format. How do I go about doing this?
What I've attempted.
final static DateFormat DATEFORMAT = new SimpleDateFormat('MM/dd/yyyy')
static constraints = {
expenseDate validator: { value ->
try {
Date date = DATEFORMAT.parse(it)
return DATEFORMAT.format(date) == it
} catch (ParseException e) {
return false
}
}
}
GSP
<div
class="form-group ${hasErrors(bean: recoveryDetailInstance, field: 'expenseDate', 'error')} required">
<label class="col-sm-4 control-label" for="expenseDate"> <g:message
code="recoveryDetailInstance.expenseDate.label" default="Expense Date" /> <span
class="required-indicator">*</span>
</label>
<div class="col-sm-8">
<g:field id="dp1" class="form-control input-sm"
name="expenseDate" type="text" data-date-format="MM/dd/yyyy" data-date="${recoveryDetailInstance?.getExpenseDateFormat()}"
value="${formatDate(format:'MM/dd/yyyy', date: recoveryDetailInstance.expenseDate)}"
disabled="${disabled}" required="" style="background:#fff"/>
</div>
</div>
This does not seem work.
So how do I format the date to MM/dd/yyyy for the frontend and then validate and convert back to a Date before an insert?