Form validation

Django Version 1.10.5

I can not find this answer in the documentation or source code. Using the sample form below, I expect my submit form validation to be run in the order I decided.

So the validators are .RegexValidator, validators.MinLengthValidator, etc. will work in that order. However, when submitting the form, it will be seen that the validators work in reverse order.

If validate_status, validate_employee_id, etc. they will work.

Is this expected?

class FormLogin(forms.Form): # Employee ID employee_id = forms.CharField( label=_('employeeId'), required=True, widget=forms.TextInput( attrs={ 'id': 'employee_id', 'placeholder': _('employeeId'), 'class': 'form-control' } ), validators=[ validators.RegexValidator('^[1-9][0-9]*$', _('validatorStartsWithZero')) validators.MinLengthValidator(1), validators.MaxLengthValidator(20), validate_employee_id, validate_status ] ) 

I currently have 1 user with id 1.

When I submit the form using 01, the validate_status validator accepts and returns that the user does not even exist. I would expect validators.RegexValidator to be returned first because it has 0 in front.

If I canceled the entire order of validators, then the check will work in the order I wanted. But now the readability of the code is unclear what really happens.

Change 1 . Purified example with additional information

+5
source share
1 answer

I wrote this little test code to reproduce this.

 from django import forms def validate_1(value): print('RUNNING VALIDATOR 1') raise ValidationError( 'validation error 1', params={'value': value}, ) def validate_2(value): print('RUNNING VALIDATOR 2') raise ValidationError( 'validation error 2', params={'value': value}, ) class FormLogin(forms.Form): # Employee ID employee_id = forms.CharField(validators=[ validate_1, validate_2 ]) 

Launch:

 >>> f = FormLogin({'employee_id': '01'}) >>> f.is_valid() RUNNING VALIDATOR 1 RUNNING VALIDATOR 2 False >>> f.errors {'employee_id': ['validation error 1', 'validation error 2']} >>> 

As you can see, validators executed in descending order.

I assume that one of your own written validators throws a ValidationError incorrectly so that the error list gets messed up or that you incorrectly display errors in your template.

Typically, all validators will start, and each validation error will be added to the error list. But they work in descending order.

+1
source

Source: https://habr.com/ru/post/1263508/


All Articles