mirror of
https://github.com/django/django.git
synced 2025-07-06 18:59:13 +00:00
[soc2009/model-validation] Slight tuning of the docs and working code
git-svn-id: http://code.djangoproject.com/svn/django/branches/soc2009/model-validation@11434 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
parent
8c98833283
commit
244296ffbc
@ -193,9 +193,9 @@ previous features.
|
||||
|
||||
Using validators
|
||||
~~~~~~~~~~~~~~~~
|
||||
.. versionadded::
|
||||
.. versionadded:: 1.2
|
||||
|
||||
Django's form- (and model-) fields support use of simple uitility functions and
|
||||
Django's form (and model) fields support use of simple utility functions and
|
||||
classes known as validators. These can be added to fields on their declaration
|
||||
as argument to ``__init__`` or defined on the Field class itself.
|
||||
|
||||
@ -209,26 +209,22 @@ look at Django's ``EmailField``::
|
||||
default_validators = [validators.validate_email]
|
||||
|
||||
As you can see, ``EmailField`` is just a ``CharField`` with customized error
|
||||
message and a validator that validates e-mail addresses. This can also be done on field definition so::
|
||||
message and a validator that validates e-mail addresses. This can also be done
|
||||
on field definition so::
|
||||
|
||||
email = forms.EmailField()
|
||||
|
||||
is equivalent to::
|
||||
|
||||
email = forms.CharField(
|
||||
error_messages={
|
||||
'invalid': _(u'Enter a valid e-mail address.'),
|
||||
},
|
||||
validators=[validators.validate_email]
|
||||
)
|
||||
email = forms.CharField(validators=[validators.validate_email],
|
||||
error_messages={'invalid': _(u'Enter a valid e-mail address.')})
|
||||
|
||||
|
||||
Form field default cleaning
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Let's firstly create a custom form field that validates its input is a string
|
||||
containing comma-separated e-mail addresses, with at least one address. The
|
||||
full class looks like this::
|
||||
containing comma-separated e-mail addresses. The full class looks like this::
|
||||
|
||||
from django import forms
|
||||
from django.core.validators import validate_email
|
||||
@ -236,13 +232,17 @@ full class looks like this::
|
||||
class MultiEmailField(forms.Field):
|
||||
def to_python(self, value):
|
||||
"Normalize data to a list of strings."
|
||||
|
||||
# return empty list on empty input
|
||||
if not value: return []
|
||||
|
||||
return value.split(',')
|
||||
|
||||
def validate(self, value):
|
||||
"Check if value consists only of valid emails."
|
||||
|
||||
# check if value is given if the field is required
|
||||
super(MultiEmailField, self).validate()
|
||||
super(MultiEmailField, self).validate(value)
|
||||
|
||||
for email in value:
|
||||
validate_email(email)
|
||||
|
Loading…
x
Reference in New Issue
Block a user