Grails 命令对象验证何时应该失败



我的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'],但都不起作用。有人有什么想法吗?谢谢。

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

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

目前,它首先评估!val,如果它不为 null 或空白,则始终如此。

最新更新