Add ValidGPC formencode validator

This commit is contained in:
Lance Edgar 2016-12-13 22:27:52 -06:00
parent f890405162
commit acbb3d289c

View file

@ -26,8 +26,11 @@ Custom Form Validators
from __future__ import unicode_literals, absolute_import from __future__ import unicode_literals, absolute_import
import re
from rattail.db import model from rattail.db import model
from rattail.db.util import validate_email_address, validate_phone_number from rattail.db.util import validate_email_address, validate_phone_number
from rattail.gpc import GPC
import formencode as fe import formencode as fe
import formalchemy as fa import formalchemy as fa
@ -35,6 +38,26 @@ import formalchemy as fa
from tailbone.db import Session from tailbone.db import Session
class ValidGPC(fe.validators.FancyValidator):
"""
Validator for fields which should contain GPC value.
"""
def _to_python(self, value, state):
if value is not None:
digits = re.sub(r'\D', '', value)
if digits:
try:
return GPC(digits)
except ValueError as error:
raise fe.Invalid("Invalid UPC: {}".format(error), value, state)
def _from_python(self, upc, state):
if upc is None:
return ''
return upc.pretty()
class ModelValidator(fe.validators.FancyValidator): class ModelValidator(fe.validators.FancyValidator):
""" """
Generic validator for data model reference fields. Generic validator for data model reference fields.