0
votes

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 :)

1
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: grails.org/doc/2.2.x/ref/Domain%20Classes/clearErrors.htmlJoshua Moore
Thank you for the hint :) now it works perfectly!gabriel
Should I add that as an answer?Joshua Moore
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: grails.org/doc/2.4.x/api/org/grails/databinding/…Nikhil Bhandari
Thank you @NikhilBhandari. Works equally well and even saves me some lines of code!gabriel

1 Answers

1
votes

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.