我的 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 或空白,那总是正确的。
关于Grails CommandObject 验证何时应该失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21914706/