0

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?

Code Junkie
  • 7,602
  • 26
  • 79
  • 141

1 Answers1

1

I would suggest use Grails tag formatDate for display purposes. Example:

<g:formatDate format="yyyy-MM-dd" date="${date}"/>

Validation on date could be constraints like 'not null' 'after today' etc. Ref SO question here

Community
  • 1
  • 1
Salman
  • 76
  • 5
  • I'm sorry, I posted my gsp code too. How do I use the date format with a input field? Does this code just get placed in the value of the field? – Code Junkie Jul 24 '15 at 19:46
  • value="${formatDate(format:'mm/dd/yyyy', date: yourDate)}" /> is what I'd need to get it to work with the GSP, still working to resolve the validation issue though. – Code Junkie Jul 24 '15 at 20:03
  • Have you considered command object? It is perfect for your case. Read up here http://www.simplicityitself.com/our-team/all-hail-command/ – Salman Jul 24 '15 at 20:08
  • I am not near a computer. This discussion is what I am referring to: http://stackoverflow.com/a/21455449/97728 – Salman Jul 24 '15 at 20:21