joshmarshall/mogo — pull request #5 by jarrodb (2011-10-29 23:37:42+00:00)
Title: (Ghetto?) Field Validation

Hey Josh,

I was just messing around with Mogo (which I love) and wanted some better Field validation. This may be a terrible way of implementing validation, but just thought I would run it by you since I started using it. Maybe this validation should be done at a higher layer like a forms class or there is already a mechanism in place to do this that I don't know about.

Here would be the basic gist of use:

from mogo import Model, Field, connect
from mogo.validator import IS_LENGTH, IS_INT_IN_RANGE

class Foo(Model):
# username - minimum length of 4, maximum length of 32
username = Field(unicode, validators=[IS_LENGTH(4,32)])
# password - minimum length of 6 and no maximum length
password = Field(unicode, validators=[IS_LENGTH(6)])
# enabled - minimum value of 0, maximum of 1
enabled = Field(int, validators=[IS_INT_IN_RANGE(0,1)])

try:
f = Foo.new(
username=u'admin',
password=u'cleartext',
enabled=2
)
except Exception, e:
# list of exception
print e.errors
# list of exceptions for one field (for templates)
print e.errors['enabled']

# {'enabled': [ValueError('maximum value is 1',)]}
# [ValueError('maximum value is 1',)]

The validators are just aliases for the objects the represent and if exceptions are raised I raise a generic ValueError exception with the member 'errors' to hold the field_name key with the 1 or more exceptions raised from the validators.