how to validate string size within bounds ?

34 views
Skip to first unread message

kanzaki

unread,
Nov 27, 2023, 10:03:24 AM11/27/23
to Grape Framework Discussion
Hi,
I'd like to check that a string parameter's size is between [100..250] characters long.

So far, I believe I can create a class "length"  as defined in the API docs:

class Length < Grape::Validations::Validators::Base def validate_param!(attr_name, params) unless params[attr_name].length <= @option raise Grape::Exceptions::Validation.new params: [@scope.full_name(attr_name)], message: "must be at the most #{@option} characters long" end end end

but is there a better more concise way to do it ?

params do
   requires: motto, type: String, length: 100..250
end

Daniel D.

unread,
Nov 28, 2023, 1:45:47 PM11/28/23
to ruby-...@googlegroups.com
This looks pretty nice and is similar to the example in https://github.com/ruby-grape/grape#custom-validators

I think it would be great to have this validator part of Grape if we can make it work across types, support min/max/etc. Want to give it a shot? 

--
You received this message because you are subscribed to the Google Groups "Grape Framework Discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ruby-grape+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ruby-grape/8b3e29b8-f687-4c71-9c09-94c9b92c7407n%40googlegroups.com.


--

dB. | Moscow - Geneva - Seattle - New York
code.dblock.org - t:@dblockdotorg - ig:@artdblockdotorggithub/dblock

Reply all
Reply to author
Forward
0 new messages