(快速參考)

錯誤

目的

包含資料繫結和/或驗證錯誤的 Spring Errors 介面實例。

範例

def user = new User(params)

if (user.validate()) {
    // do something with user
}
else {
    user.errors.allErrors.each {
        println it
    }
}

說明

errors 屬性在 資料繫結期間由 Grails 使用,用於儲存類型轉換錯誤,並在呼叫 validatesave 方法時在 驗證期間使用。

您也可以使用 rejectrejectValue 方法新增自己的錯誤

if (params.password != params.confirm_password) {

    user.errors.reject(
        'user.password.doesnotmatch',
        ['password', 'class User'] as Object[],
        '[Property [{0}] of class [{1}] does not match confirmation]')

    // The following helps with field highlighting in your view
    user.errors.rejectValue(
        'password',
        'user.password.doesnotmatch')

    render(view: 'signup', model: [user: user])
}

在上述 reject 範例中,'user.password.doesnotmatch' 是對應於 grails-app/i18n/message.properties 中值的錯誤代碼,\['password', 'class User'\] as Object\[\] 是從 List 轉換為 Object 陣列的 Groovy 轉換,以符合預期的簽章,而 '\[Property \[{0}\] of class \[{1}\] does not match confirmation\]' 是預設對應字串。

rejectValue 範例中,'password' 是使用 <g:hasErrors> 標籤突顯顯示的檢視欄位,而 'user.password.doesnotmatch' 是 i18n 錯誤代碼。