#27263: Allow validators to short-circuit in form field validation
---------------------------------+-----------------------------------------
     Reporter:  Alexey Rogachev  |                    Owner:  nobody
         Type:  New feature      |                   Status:  new
    Component:  Forms            |                  Version:  master
     Severity:  Normal           |               Resolution:
     Keywords:  form, validator  |             Triage Stage:  Someday/Maybe
    Has patch:  0                |      Needs documentation:  0
  Needs tests:  0                |  Patch needs improvement:  0
Easy pickings:  0                |                    UI/UX:  0
---------------------------------+-----------------------------------------

Comment (by Alexey Rogachev):

 Based on [https://code.djangoproject.com/ticket/27263#comment:8 idea of
 Aymeric Augustin] I've come up with this workaround:

 {{{#!python
 class MultiValidator(object):
     def __init__(self, validators):
         self.validators = validators

     def __call__(self, value):
         for validator in self.validators:
             validator(value)
 }}}

 Then we can group multiple validators using this `MultiValidator`:

 {{{#!python
 class ChartForm(forms.ModelForm):
     import_file = forms.FileField(required=False, label='File for import',
 validators=[MultiValidator([
         FileSizeValidator(max_size='500 kb'),
         FileTypeValidator(extensions=('xlsx',)),
     ])])
 }}}

 I don't like the additional nesting and mess with brackets, but besides
 that I think it's OK.

 We can improve the look by subclassing and creating specific class:

 {{{#!python
 class ChartFileMultiValidator(MultiValidator):
     def __init__(self):
         validators = [
             FileSizeValidator(max_size='500 kb'),
             FileTypeValidator(extensions=('xlsx',)),
         ]
         super(ChartFileMultiValidator, self).__init__(validators)
 }}}

 Then the code reduces to:

 {{{#!python
 class ChartForm(forms.ModelForm):
     import_file = forms.FileField(required=False, label='File for import',
 validators=[ChartFileMultiValidator])
 }}}

 I personally prefer first approach.

 In this case maybe add info about default strategy of applying validators
 for form field and possible option for short circuit validation to
 documentation?

--
Ticket URL: <https://code.djangoproject.com/ticket/27263#comment:11>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/067.5c83abcb81f8bb3ed2d351911e7f4e31%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to