0

我的 Grails 2.2.3 应用程序中有以下命令对象。

@Validateable
class PictureCommand {

    MultipartFile picture
    String notes
    Boolean isDocument

    static constraints = {
        picture nullable: false, validator: { val ->
            if (!val.contentType in ['image/jpeg', 'image/png', 'image/pjpeg', 'image/gif','image/bmp'])
                return 'fileType.invalid'
        }
        notes nullable: true
        isDocument nullable: true
    }
}

这允许上传图片文件,并确保它在有效类型列表中。但是,问题是我可以上传不在该列表中的文件。当我打电话时cmd.validate()我得到true,然后我打电话cmd.hasErrors()得到false。我试过返回字符串'fileType.invalid'和列表['fileType.invalid'],但都不起作用。有没有人有任何想法?谢谢。

4

1 回答 1

2

您需要一些括号来获得正确的运算符顺序:

if (!(val.contentType in ['image/jpeg', 'image/png', 'image/pjpeg', 'image/gif','image/bmp']))

目前它!val首先评估,如果它不为空或空白,那总是正确的。

于 2014-02-20T17:55:04.270 回答