0

I'm trying to set the date of birth of a person using jQuery Datepicker. However, all I get is that the Property dateOfBirth must be a valid Date.

So, originally, my controller looks like this:

def update(Person personInstance) {
    if (personInstance == null) {
        // do Something
        return
    }

    if (personInstance.hasErrors()) {
        respond personInstance.errors, view: 'edit'
        return
    }

    // do the rest
}

I figured out, that with jQuery I should use a SimpleDateFormat object in order to generate a proper Date object. Nevertheless, even if I directly assign a new Date object to dateOfBirth and subsequently validating the personInstance domain object - like in the following code segment - I still get the Property dateOfBirth must be a valid Date error.

def update(Person personInstance) {
    if (personInstance == null) {
        // do Something
        return
    }

    // added code
    personInstance.dateOfBirth = new Date()
    personInstance.validate()
    // added code

    if (personInstance.hasErrors()) {
        respond personInstance.errors, view: 'edit'
        return
    }

    // do the rest
}

Thank you for any help :)

gabriel
  • 347
  • 3
  • 18
  • 2
    The reason why you are still seeing errors is because validation is automatically called after binding your command/domain object. Use `personInstance.clearErrors()` before calling `personInstance.validate()` manually. You can see more about this in the documentation: http://grails.org/doc/2.2.x/ref/Domain%20Classes/clearErrors.html – Joshua Moore Sep 01 '14 at 08:27
  • 1
    Should I add that as an answer? – Joshua Moore Sep 01 '14 at 09:06
  • You can also use the @BindingFormat annotation above the field to bind the date in the format its received from the client side. More on this here: http://grails.org/doc/2.4.x/api/org/grails/databinding/BindingFormat.html – Nikhil Bhandari Sep 01 '14 at 15:04
  • Thank you @NikhilBhandari. Works equally well and even saves me some lines of code! – gabriel Sep 03 '14 at 12:38

1 Answers1

1

The reason why you are still seeing errors is because validation is automatically called after binding your command/domain object when the method is called.

Use personInstance.clearErrors() before calling personInstance.validate() manually to clear out any existing binding/validation errors. You can see more about this in the documentation.

Joshua Moore
  • 24,706
  • 6
  • 50
  • 73