Validation Groovy 2.4.4命令对象-重用验证器闭包
假设我有以下命令:Validation Groovy 2.4.4命令对象-重用验证器闭包,validation,groovy,command-objects,Validation,Groovy,Command Objects,假设我有以下命令: @Validateable class MyCommand { String cancel_url String redirect_url String success_url static constraints = { cancel_url nullable: false, validator: { url, obj -> //some specific validation
@Validateable
class MyCommand {
String cancel_url
String redirect_url
String success_url
static constraints = {
cancel_url nullable: false, validator: { url, obj ->
//some specific validation
//some common url validation
}
redirect_url nullable: false, validator: { url, obj ->
//some specific validation
//some common url validation
}
success_url nullable: false, validator: { url, obj ->
//some specific validation
//some common url validation
}
}
}
假设我想对任何URL字段执行一些常见的验证(例如,检查是否允许该域)。什么样的语法可以将这个常见的验证代码分解成一个单独的函数,而不是在每个验证闭包中放入相同的块?您是否尝试从几个trait继承(或者说实现)您的命令
Trait CancelComponentCommand {
String cancelUrl
static constraints = {
cancelUrl validator: { url, obj ->
//some specific validation
//some common url validation
}
}
}
Trait RedirectComponenCommand {
String redirectUrl
static constraints = {
redirectUrl validator: { url, obj ->
//some specific validation
//some common url validation
}
}
}
@Validateable
class MyCommand implements CancelComponentCommand, RedirectComponenCommand {
}
PS无需设置可空:false
,默认为false。另外,如果使用camelCase编写字段,代码的可读性会更好。您是否尝试从几个trait继承(或者说实现)您的命令
Trait CancelComponentCommand {
String cancelUrl
static constraints = {
cancelUrl validator: { url, obj ->
//some specific validation
//some common url validation
}
}
}
Trait RedirectComponenCommand {
String redirectUrl
static constraints = {
redirectUrl validator: { url, obj ->
//some specific validation
//some common url validation
}
}
}
@Validateable
class MyCommand implements CancelComponentCommand, RedirectComponenCommand {
}
PS无需设置
可空:false
,默认为false。如果使用camelCase编写字段,代码的可读性也会大大提高。谢谢提示!谢谢你的提示!