From acbb3d289c4dd2e595ec0e625ab7e8bc23870773 Mon Sep 17 00:00:00 2001 From: Lance Edgar Date: Tue, 13 Dec 2016 22:27:52 -0600 Subject: [PATCH] Add `ValidGPC` formencode validator --- tailbone/forms/validators.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/tailbone/forms/validators.py b/tailbone/forms/validators.py index 6ccfed88..ecd738c9 100644 --- a/tailbone/forms/validators.py +++ b/tailbone/forms/validators.py @@ -26,8 +26,11 @@ Custom Form Validators from __future__ import unicode_literals, absolute_import +import re + from rattail.db import model from rattail.db.util import validate_email_address, validate_phone_number +from rattail.gpc import GPC import formencode as fe import formalchemy as fa @@ -35,6 +38,26 @@ import formalchemy as fa 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): """ Generic validator for data model reference fields.