Refactor to use validator class

Using a separate validator class to check for appropriate characters in
a text message sender means that we’re not doing this validation in a
different way from the other checks (length and required). So the code
is cleaner.
This commit is contained in:
Chris Hill-Scott
2018-01-31 10:26:37 +00:00
parent 532458cf3c
commit b11653fe08
3 changed files with 25 additions and 8 deletions

View File

@@ -1,3 +1,4 @@
import re
from wtforms import ValidationError
from notifications_utils.field import Field
from notifications_utils.gsm import get_non_gsm_compatible_characters
@@ -63,3 +64,15 @@ class OnlyGSMCharacters:
('It' if len(non_gsm_characters) == 1 else 'They')
)
)
class LettersAndNumbersOnly:
regex = re.compile(r'^[a-zA-Z0-9\s]+$')
def __init__(self, message='Use letters and numbers only'):
self.message = message
def __call__(self, form, field):
if field.data and not re.match(self.regex, field.data):
raise ValidationError(self.message)