创建自定义验证器 [英] Create custom Validator
本文介绍了创建自定义验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我应该如何创建并配置一个验证器类,以将其用作域类约束?例如:
class链接{
字符串url
静态约束= {url url:true}
动机:Grails UrlValidator尽管不允许下划线它是有效的,请参阅 rfc2396,第2.3节。未保留字符。 验证器(作为静态属性)并将它们引用到相关的域类中。
// src / groovy $ b $ class MyValidators {
static urlCheck = {url,obj - >
//自定义网址验证转到此处。
}
}
class链接{
字符串url
静态约束= {
url验证器:MyValidators.urlCheck
}
$ b $ p
$ b如果不需要将验证程序外部化到单独的实用程序类,可以直接在domain类中使用验证器:
static constraints = {
url验证器:{value,obj - > ...}
}
How should I create and configure a validator class to use it as a domain class constraint? For example:
class Link {
String url
static constraints = { url url:true }
}
Motivation: Grails UrlValidator does not allow underline character despite it being valid, see rfc2396, section 2.3. Unreserved Characters.
解决方案 You can have a utility class in src/groovy
with required validators (as static properties) and refer them in the concerned domain class.
//src/groovy
class MyValidators{
static urlCheck = {url, obj ->
//custom validation for url goes here.
}
}
class Link {
String url
static constraints = {
url validator: MyValidators.urlCheck
}
}
If there is no need to externalize the validator to a separate utility class then you can directly use the validator in domain class as:
static constraints = {
url validator: {value, obj -> ...}
}
这篇关于创建自定义验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文