将字符串验证为整数范围的 Grails 最佳实践
我正在尝试验证 SELECT。通常我会使用 inList,因为 SELECT 意味着固定数量的字符串,但我想知道是否有更优雅的东西。在本例中,我有一个带有 SELECT 输入的表单,其值为 0-24,对应于接下来的 24 个月。
在我的 cmdObject 中,我
class FormCommand {
String startSlot
static constraints = {
// startSlot(nullable:false, blank:false, range:0..24)
startSlot(nullable:false, blank:false,
validator: { val, obj -> val.toInteger() < 25})
}
}
希望能够使用 range:0..24 语句,但根据我对范围的理解,它们不适用于表单生成的字符串。
有没有一种首选方法可以将传入字符串强制转换/绑定为 int 以便我可以使用范围:0..24?或者还有其他方法来处理这个问题吗?
我可以做
inList: [ "0", "1", /* type them all out */, "24" ]
或编写一些更强大的自定义验证器,但我想知道是否有更 groovy/grails 解决方案。
谢谢。
I'm trying to validate a SELECT. Normally I'd use an inList, as SELECT implies a fixed number of strings, but i was wondering if there was something more elegant. In this case, I have a form with a SELECT input that has the values 0-24 as , corresponding to the next 24 months.
In my cmdObject I have
class FormCommand {
String startSlot
static constraints = {
// startSlot(nullable:false, blank:false, range:0..24)
startSlot(nullable:false, blank:false,
validator: { val, obj -> val.toInteger() < 25})
}
}
I'd like to be able to use the range:0..24 statement, but from what I understand of ranges, they doesn't apply to Strings generated by the form.
Is there a preferred way to either cast/bind the incoming string into an int so I can use the range:0..24? Or is there another way to handle this?
I could do
inList: [ "0", "1", /* type them all out */, "24" ]
or write some more robust custom validators, but I'm wondering if there's a more groovy/grails solution.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以将范围与字符串一起使用,如下所示......
You can use ranges with Strings like so...
我会使用范围。请参阅文档
http://grails.org/doc/1.0.x/ref /Constraints/range.html
我认为 size 是针对 String 的,更像是一个长度的东西
I would use range. See documentation
http://grails.org/doc/1.0.x/ref/Constraints/range.html
I think size is for String and more like a length thing
最终的答案涉及这里建议的组合:
文档位于 ( http ://grails.org/doc/latest/ref/Constraints/range.html )当它说它可以用于带有下一个/上一个的任何东西时,让我很失望。我不知道您可以通过将字段指定为 Integer 来隐式地将 param.startSlot 转换为 Integer。
谢谢。
The final answer turned out to involve a combination of the suggestions here:
The documentation at ( http://grails.org/doc/latest/ref/Constraints/range.html ) threw me off when it said it could be used on anything with a next / previous. I didnt know that you could implicitly cast the param.startSlot into an Integer simply by specifying the field as Integer.
Thanks.