Search code examples
grails

populating own error-messages to the grails domain errors


I'd like to know, if (and how) I could append some own error-messages to the domain-object after (or before) a validation.

My intention is, I have to check the uploaded file in a form for some attributes (image size etc.) and if something is wrong, I would like to add an error-message which is displayed in the usual grails ".hasErrors" loop.

(And I think I need to have the possibility to express errors in some cross-domain check failure...)

Thanks in advance, Susanne.


Solution

  • You can add custom validation errors as described in the errors docs as follows:

    class SampleController {
    
    def save() {
      def sampleObject = new SampleObject(params)
      sampleObject.validate()
    
      if(imageSizeIsTooBig(sampleObject)) {
        sampleObject.errors.rejectValue(
          'uploadedFile',
          'sampleObject.uploadedFile.sizeTooBig'
        )    
    }
    
    private def imageSizeIsTooBig(SampleObject sampleObject) {
      // calculation on sampleObject, if size is too big
    }
    

    Perhaps, you could even handle your case with a custom validator, so you can call validate() one time and be sure, that all constraints are fulfilled.