def validate (type_, allow_none=False, default=None):
    """Create a validator for a field in an epgdb record.

type_: Class to expect the value to be an instance of
allow_none: Whether the value should pass validation if it's `None`
default: Value to use if `None` is allowed and the value is `None`

Returns a function which accepts the value and returns the value to use or
throws `ValueError`.

"""
    def validate_fn (value):
        if value is None:
            if allow_none:
                return default
            else:
                raise ValueError('field is missing')
        if not isinstance(value, type_):
            raise ValueError('expected: {}; got: {}'.format(type_, repr(value)))
        return value

    return validate_fn