Adrian Rodriguez
Adrian Rodriguez

Reputation: 453

Grails Custom Validation with List of objects

I already have a custom validation for a MultipartFile.

class ImageCommand implements Validateable {
MultipartFile imageFile

static constraints = {
    imageFile  validator: { val, obj ->
        if ( val == null ) {
            return false
        }
        if ( val.empty ) {
            return false
        }

        ['jpeg', 'jpg', 'png'].any { extension ->
            val.originalFilename?.toLowerCase()?.endsWith(extension)
        }
    }
}}

But I will need more than one file now, I would like to change the custom validation to get a List and apply the constraint.

<input type="file" id="imageFile1" name="imageFile">
to
<input type="file" id="imageFile1" name="imageFiles">
<input type="file" id="imageFile2" name="imageFiles">

Any idea how to work with collections in custom validations???

Upvotes: 0

Views: 349

Answers (1)

gregorr
gregorr

Reputation: 406

You will get a List<MultipartFile> imageFiles if the inputs are named same. So you have to adjust your validator to work with a list:

static constraints = {
    imageFiles validator: { val, obj ->
        val && val.every { imgFile ->
            if ( imgFile == null ) {
                return false
            }
            if ( imgFile.empty ) {
                return false
            }

            ['jpeg', 'jpg', 'png'].any { extension ->
                imgFile.originalFilename?.toLowerCase()?.endsWith(extension)
            }
        }
    }
}

Upvotes: 1

Related Questions