Refactor RequiredIfNot custom validator, add tests
This commit is contained in:
@@ -10,9 +10,9 @@ from wtforms.fields import (
|
||||
)
|
||||
from wtforms.fields.html5 import DateField, TelField
|
||||
from wtforms.widgets import ListWidget, CheckboxInput
|
||||
from wtforms.validators import Required, Length, StopValidation
|
||||
from wtforms.validators import Required, Length
|
||||
|
||||
from atst.forms.validators import IsNumber, PhoneNumber
|
||||
from atst.forms.validators import IsNumber, PhoneNumber, RequiredIfNot
|
||||
|
||||
from .forms import CacheableForm
|
||||
from .data import (
|
||||
@@ -26,24 +26,6 @@ from .data import (
|
||||
from atst.utils.localization import translate
|
||||
|
||||
|
||||
class RequiredIfNot(Required):
|
||||
# a validator which makes a field required only if
|
||||
# another field has a falsy value
|
||||
|
||||
def __init__(self, other_field_name, *args, **kwargs):
|
||||
self.other_field_name = other_field_name
|
||||
super(RequiredIfNot, self).__init__(*args, **kwargs)
|
||||
|
||||
def __call__(self, form, field):
|
||||
other_field = form._fields.get(self.other_field_name)
|
||||
if other_field is None:
|
||||
raise Exception('no field named "%s" in form' % self.other_field_name)
|
||||
if not bool(other_field.data):
|
||||
super(RequiredIfNot, self).__call__(form, field)
|
||||
else:
|
||||
raise StopValidation()
|
||||
|
||||
|
||||
class AppInfoForm(CacheableForm):
|
||||
portfolio_name = StringField(
|
||||
translate("forms.task_order.portfolio_name_label"),
|
||||
|
@@ -1,5 +1,5 @@
|
||||
import re
|
||||
from wtforms.validators import ValidationError
|
||||
from wtforms.validators import ValidationError, StopValidation
|
||||
import pendulum
|
||||
from datetime import datetime
|
||||
from atst.utils.localization import translate
|
||||
@@ -78,3 +78,18 @@ def ListItemsUnique(message=translate("forms.validators.list_items_unique_messag
|
||||
raise ValidationError(message)
|
||||
|
||||
return _list_items_unique
|
||||
|
||||
|
||||
def RequiredIfNot(other_field_name, message=translate("forms.validators.is_required")):
|
||||
def _required_if_not(form, field):
|
||||
other_field = form._fields.get(other_field_name)
|
||||
if other_field is None:
|
||||
raise Exception('no field named "%s" in form' % self.other_field_name)
|
||||
|
||||
if not bool(other_field.data):
|
||||
if field.data is None:
|
||||
raise ValidationError(message)
|
||||
else:
|
||||
raise StopValidation()
|
||||
|
||||
return _required_if_not
|
||||
|
Reference in New Issue
Block a user