1

假设我有以下命令:

@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 字段执行一些常见的验证(例如,检查是否允许该域)。将这个常见的验证代码分解成一个单独的函数而不是在每个验证闭包中放置相同的块的语法是什么?

4

1 回答 1

0

您是否尝试从多个特征继承(或者说实现)您的命令?

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 无需设置nullable: false,默认为false。此外,如果字段是使用 camelCase 编写的,那么代码的可读性也会更高。

于 2017-04-18T19:59:44.303 回答