Form handling and validation (bottle_utils.form)

Validation

class bottle_utils.form.validators.Validator(messages={})[source]

Base validator class. This calss does not do much on its own. It is used primarily to build other validators.

The validate() method in the subclass performs the validation and raises a ValidationError exception when the data is invalid.

The messages argument is used to override the error messages for the validators. This argument should be a dictionary that maps the error names used by individual validators to the new messages. The error names used by validators is documented for each class. You can also dynamically obtain the names by inspecting the messages property on each of the validator classes.

messages = {}

Mapping between errors and their human-readabile messages

validate(data)[source]

Perform actual validation over data. Should raise ValidationError if data does not pass the validation.

Two arguments are passed to the validation error, the error name and a dictionary with extra parameters (usually with value key that points to the value).

Error message is constructed based on the arguments, passed to the exception by looking up the key in the messages property to obtain the message, and then interpolating any extra parameters into the message.

This method does not need to return anything.

class bottle_utils.form.validators.DateValidator(messages={})[source]

Validates date fields. This validator attempts to parse the data as date (or date/time) data. When the data cannot be parsed, it fails.

Error name(s):date
class bottle_utils.form.validators.InRangeValidator(min_value=None, max_value=None, **kwargs)[source]

Validates that value is within a range between two values. This validator works with any objects that support > and < operators.

The min_value and max_value arguments are used to set the lower and upper bounds respectively. The check for those bounds are only done when the arguments are supplied so, when both arguments are omitted, this validator is effectively pass-through.

Error name(s):min_val, max_val
class bottle_utils.form.validators.LengthValidator(min_len=None, max_len=None, **kwargs)[source]

Validates that value’s length is within specified range. This validator works with any objects that support the len() function.

The min_len and max_len arguments are used to set the lower and upper bounds respectively. The check for those bounds are only done when the arguments are supplied so, when both arguments are omitted, this validator is effectively pass-through.

Error name(s):min_len, max_len
class bottle_utils.form.validators.Required(messages={})[source]

Validates the presence of data. Technically, this validator fails for any data that is an empty string, a string that only contains whitespace, or data that is not a string and evaluates to False when coerced into boolean (e.g., 0, empty arrays and dicts, etc).

Error name(s):required
class bottle_utils.form.exceptions.ValidationError(message, params=None, is_form=False)[source]

Error raised during field and form validation. The erorr object can be initialized using a message string, and two optional parameters, params and is_form.

The params is a dictionary of key-value pairs that are used to fill the message in with values that are only known at runtime. For example, if the message is '{value} is invalid for this field', we can pass a params argument that looks like {'value': foo}. The format() method is called on the message.

Note that message is a key pointing to a value in the messages dictionary on the form and field objects, not the actual message.

Fields

class bottle_utils.form.fields.DormantField(field_cls, args, kwargs)[source]

Proxy for unbound fields. This class holds the the field constructor arguments until the data can be bound to it.

You never need to use this class directly.

class bottle_utils.form.fields.Field(label=None, validators=None, value=None, name=None, messages={}, **options)[source]

Form field base class. This class provides the base functionality for all form fields.

The label argument is used to specify the field’s label.

The validators argument is used to specify the validators that will be used on the field data.

If any data should be bound to a field, the value argument can be used to specify it. Value can be a callable, in which case it is called and its return value used as value.

The name argument is used to specify the field name.

The messages argument is used to customize the validation error messages. These override any messages found in the messages attribute.

Any extra keyword attributes passed to the constructor are stored as options property on the instance.

exception ValidationError(message, params=None, is_form=False)

Error raised during field and form validation. The erorr object can be initialized using a message string, and two optional parameters, params and is_form.

The params is a dictionary of key-value pairs that are used to fill the message in with values that are only known at runtime. For example, if the message is '{value} is invalid for this field', we can pass a params argument that looks like {'value': foo}. The format() method is called on the message.

Note that message is a key pointing to a value in the messages dictionary on the form and field objects, not the actual message.

Field.bind_value(value)[source]

Binds a value. This method also sets the is_value_bound property to True.

Field.generic_error

Generic error message to be used when no messages match the validation error.

Field.is_valid()[source]

Validate form field and return True is data is valid. If there is an error during Validation, the error object is stored in the _error property. Before validation, the raw value is processed using the parse() method, and stored in processed_value attribute.

When parsing fails with ValueError exception, a ‘generic’ error is stored. The default message for this error is stored in the generic_error property, and can be customized by passing a 'generic' message as part of the messages constructor argument.

Field.is_value_bound = None

Whether value is bound to this field

Field.label = None

Field label

Field.messages = {}

Validation error messages.

Field.name = None

Field name

Field.options = None

Extra keyword argument passed to the constructor

Field.parse(value)[source]

Parse the raw value and convert to Python object. Subclasses should return the value in it’s correct type. In case the passed in value cannot be cast into it’s correct type, the method should raise a ValueError exception with an appropriate error message.

Field.processed_value = None

Processed value of the field

Field.type = 'text'

Field markup type. This is arbitrary and normally used in the templates to differentiate between field types. It is up to the template author to decide how this should be treated.

Field.validators = None

Field validators

Field.value = None

Raw value of the field

class bottle_utils.form.fields.BooleanField(label=None, validators=None, value=None, default=False, **options)[source]

Field for working with boolean values.

Two additional constructor arguments are added. The default argument is used to specify the default state of the field, which can be used in the template to, for instance, check or uncheck a checkbox or radio button. The expected_value is the base value of the field against which the bound value is checked: if they match, the Python value of the field is True.

Python type:bool
Type:checkbox
default = None

Default state of the field

expected_value = None

Base value of the field against which bound value is checked

class bottle_utils.form.fields.DateField(label=None, validators=None, value=None, **options)[source]

Field for working with dates. This field overloads the base class’ constructor to add a DateValidator.

Python type:str (unicode in Python 2.x)
Type:text
class bottle_utils.form.fields.EmailField(label=None, validators=None, value=None, name=None, messages={}, **options)[source]

Field for working with emails.

Python type:str (unicode in Python 2.x)
Type:text
class bottle_utils.form.fields.ErrorMixin[source]

Mixin class used to provide error rendering functionality.

error

Human readable error message. This property evaluates to empty string if there are no errors.

class bottle_utils.form.fields.FileField(label=None, validators=None, value=None, name=None, messages={}, **options)[source]

Field for working with file uploads.

Python type:raw value
Type:file
class bottle_utils.form.fields.FloatField(label=None, validators=None, value=None, name=None, messages={}, **options)[source]

Field for working with floating-point numbers.

Python type:float
Type:text
class bottle_utils.form.fields.HiddenField(label=None, validators=None, value=None, name=None, messages={}, **options)[source]

Field for working with hidden inputs.

Python type:str (unicode in Python 2.x)
Type:hidden
class bottle_utils.form.fields.IntegerField(label=None, validators=None, value=None, name=None, messages={}, **options)[source]

Field for working with integers.

Python type:int
Type:text
class bottle_utils.form.fields.PasswordField(label=None, validators=None, value=None, name=None, messages={}, **options)[source]

Field for working with passwords.

Python type:str (unicode in Python 2.x)
Type:password
class bottle_utils.form.fields.SelectField(label=None, validators=None, value=None, choices=None, **options)[source]

Field for dealing with select lists.

The choices argument is used to specify the list of value-label pairs that are used to present the valid choices in the interface. The field value is then checked against the list of value and the parser validates whether the supplied value is among the valid ones.

Python type:str (unicode in Python 2.x)
Type:select
choices = None

Iterable of value-label pairs of valid choices

class bottle_utils.form.fields.StringField(label=None, validators=None, value=None, name=None, messages={}, **options)[source]

Field for working with string values.

Python type:str (unicode in Python 2.x)
Type:text
class bottle_utils.form.fields.TextAreaField(label=None, validators=None, value=None, name=None, messages={}, **options)[source]

Field for working with textareas.

Python type:str (unicode in Python 2.x)
Type:textarea

Forms

class bottle_utils.form.forms.Form(data=None, messages={})[source]

Base form class to be subclassed. To define a new form subclass this class:

class NewForm(Form):
    field1 = Field('Field 1')
    field2 = Field('Field 2', [Required])

Forms support field pre- and post-procesors. These methods are named after the field names by prepending preprocess_ and postprocess_ respectively. For example:

class NewForm(Form):
    field1 = Field('Field 1')
    field2 = Field('Field 2', [Required])

    def preprocess_field1(self, value):
        return value.replace('this', 'that')

    def postprocess_field1(self, value):
        return value + 'done'

Preprocessors can be defined for individual fields, and are ran before any validation happens over the field’s data. Preprocessors are also allowed to raise ValidationError, though their actual purpose is to perform some manipulation over the incoming data, before it is passed over to the validators. The return value of the preprocessor is the value that is going to be validated further.

Postprocessors perform a similar purpose as preprocessors, except that they are invoked after field-level validation passes. Their return value is the value that is going to be the stored as cleaned / validated data.

exception ValidationError(message, params=None, is_form=False)

Error raised during field and form validation. The erorr object can be initialized using a message string, and two optional parameters, params and is_form.

The params is a dictionary of key-value pairs that are used to fill the message in with values that are only known at runtime. For example, if the message is '{value} is invalid for this field', we can pass a params argument that looks like {'value': foo}. The format() method is called on the message.

Note that message is a key pointing to a value in the messages dictionary on the form and field objects, not the actual message.

Form.field_errors

Dictionary of all field error messages. This property maps the field names to error message maps. Field names are mapped to fields’ messages property, which maps error type to actual message. This dictionary can also be used to modify the messages because message mappings are not copied.

Form.field_messages

Alias for field_errors retained for

Form.fields

Dictionary of all the fields found on the form instance. The return value is never cached so dynamically adding new fields to the form is allowed.

Form.generic_error
Form.is_valid()[source]

Perform full form validation over the initialized form. The method has the following side-effects:

  • in case errors are found, the form’s errors container is going to be populated accordingly.
  • validated and processed values are going to be put into the processed_data dictionary.

Return value is a boolean, and is True is form data is valid.

Form.validate()[source]

Perform form-level validation, which can check fields dependent on each other. The function is expected to be overridden by implementors in case form-level validation is needed, but it’s optional. In case an error is found, a ValidationError exception should be raised by the function.