开发者

Grails best practice for validating string as integer range

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 constraint开发者_运维百科s = {
      // 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.


You can use ranges with Strings like so...

class FormCommand {

  String startSlot

  static constraints = {
      startSlot(nullable: false, size: '0'..'24')
  }
}


class FormCommand {

  Integer startSlot

  static constraints = {
      startSlot(nullable: false, size: 0..24)
  }
}


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


The final answer turned out to involve a combination of the suggestions here:

class FormCommand {

  Integer startSlot

  static constraints = {
     startSlot(nullable: false, range: 0 .. 24)
  }
}

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜