Skip to content

Custom Validation

mosop edited this page Jan 22, 2017 · 16 revisions

You can validate parsed values in your own way by setting callbacks.

A callback is a Proc object that is called after a parser process ends. optarg implements its callback features by the Crystal Callback library. For more information about the library, see README.

To set callbacks, use the .on_validate method of the Parser class that is automatically defined inside your model class.

class Hello < Optarg::Model
  arg "smiley"

  Parser.on_validate do |parser, data|
    parser.invalidate! "That's not a smile." if data.smiley != ":)"
  end
end

Hello.parse %w(:P) # => raises "That's not a smile."

A callback is called with a Optarg::Parser object and a model instance.

If a value is invalid, call Parser#invalidate! with a message. The method raises an Optarg::ValidationError exception.

Clone this wiki locally