Skip to content
Myr

Added validation to docs

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent f5b2e39 · Browse files · 1 file+41 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+41 added−0 removed

  • other:+41 added−0 removed

1 file+41 added−0 removed

modified:docs/options.rst+41 added
523 unmodified lines
524 invoke(repeat, args=['--count=1000', '--digit=12'])525526If you pass ``None`` for any of the edges it means that the range is open527at that side.528529Callbacks for Validation530------------------------531532.. versionchanged:: 2.0533534If you want to apply custom validation logic you can do this in the535parameter callbacks. These callbacks can both modify values as well as536raise errors if the validation does not work.537538In Click 1.0 you can only raise the :exc:`UsageError` but starting with539Click 2.0 you can also raie the :exc:`BadParameter` error which has the540added advantage that it will automatically format the error message to541also contain the parameter name.542543Example:544545.. click:example::546547 def validate_rolls(ctx, value):548 try:549 rolls, dice = map(int, value.split('d', 2))550 return (dice, rolls)551 except ValueError:552 raise click.BadParameter('rolls need to be in format NdM')553554 @click.command()555 @click.option('--rolls', callback=validate_rolls, default='1d6')556 def roll(rolls):557 click.echo('Rolling a %d-sided dice %d time(s)' % rolls)558559 if __name__ == '__main__':560 roll()561562And what it looks like:563564.. click:run::565566 invoke(roll, args=['--rolls=42'])567 println()568 invoke(roll, args=['--rolls=2d12'])