验证domain对象
对象
class Song { String title String artist Integer duration static constraints = { title(blank: false) artist(blank: false) duration(min: 1) } }
验证
// -68 是一个无效的值 def song = new Song(title:'The Rover', artist:'Led Zeppelin', duration:-68) if(song.save()) { println "Song was created!" } else { song.errors.allErrors.each { println it.defaultMessage } }
Error接口
package org.springframework.validation interface Errors { List getAllErrors(); int getErrorCount(); FieldError getFieldError(String feldName); int getFieldErrorCount(); List getFieldErrors(String feldName); Object getObjectName(); boolean hasErrors(); boolean hasFieldErrors(String feldName); // ... remaining methods }
重新验证操作
def song = new Song(title:'The Rover', duration:339) if(!song.validate()) { song.clearErrors() song.artist = 'Led Zeppelin' song.validate() }
自定义约束
class User { static constraints = { password(unique:true, length:5..15, validator:{val, obj -> if(val?.equalsIgnoreCase(obj.frstName)) { return false } }) }