创建自定义验证器

lsb*_*org 0 validation grails

我应该如何创建和配置验证器类以将其用作域类约束?例如:

class Link {
    String url
    static constraints = { url url:true }
}
Run Code Online (Sandbox Code Playgroud)

动机:Grails UrlValidator尽管有效,但不允许使用下划线字符,请参阅rfc2396,第2.3节.未保留的角色.

dma*_*tro 5

您可以src/groovy使用必需的验证器(作为静态属性)使用实用程序类,并在相关的域类中引用它们.

//src/groovy
class MyValidators{
    static urlCheck = {url, obj ->
        //custom validation for url goes here.
    }
}

class Link {
    String url
    static constraints = { 
        url validator: MyValidators.urlCheck 
    }
}
Run Code Online (Sandbox Code Playgroud)

如果不需要将验证器外部化为单独的实用程序类,则可以直接在域类中使用验证器:

static constraints = {
    url validator: {value, obj -> ...} 
}
Run Code Online (Sandbox Code Playgroud)