简体   繁体   English

对grails域约束进行多个条件检查?

[英]multiple condition checks on grails domain constraints?

For a domain such as 对于诸如

class Question {

    String questionText
    Type questionType

    static hasMany = [choices: Option]          
}

I was wondering if this type of conditional constraint is possible. 我想知道这种条件约束是否可能。 I want the constraint to be such that if the questionType is either (radio, checkbox, dropdown) and (&&) choices.size() == 0 then constraint is violated and error is thrown. 我希望约束是这样的,如果questionType是(无线电,复选框,下拉列表)和(&&) choices.size() == 0那么约束就会被违反并且会引发错误。 I know the second part of the condition ie to check size of collection can be done with size parameter but I was wondering if we can have complex conditions like above ie multiple conditions checks with && operators. 我知道条件的第二部分,即检查集合的大小可以使用size参数来完成,但是我想知道我们是否可以像上面那样具有复杂的条件,即使用&&运算符进行多个条件检查。

So you need custom validator. 因此,您需要自定义验证器。 Something like below should do the job. 像下面这样的事情应该做的工作。 Take a look at Grails documentation - it's quite convenient. 看一下Grails文档 -相当方便。

static constraints = {
    questionType validator: { val, obj -> 
        !(val in [Type.Radio, Type.Checkbox, Type.Dropdown] && obj.choices.isEmpty()) 
    }
}

But then you'll get error message generated by grails. 但是随后您将收到由grails生成的错误消息。 It's good to provide more readable validation error. 最好提供更具可读性的验证错误。 You can return custom message code and define it in messages.properties : 您可以返回自定义消息代码,并在messages.properties定义它:

static constraints = {
    questionType validator: { val, obj -> 
        if (val in [Type.Radio, Type.Checkbox, Type.Dropdown] && obj.choices.isEmpty())         
            return 'emptyChoicesErrorMessage'
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM