quick search:
 

RegexField for Formulator

Submitted by: philikon
Last Edited: 2005-07-15

Category: Product Development

Average rating is: 4.75 out of 5 (4 ratings)

Description:
Regular expressions aren't part of Formulator. Only God and Martijn know why the hell that is. So, here's a Formulator Field that validates against a regular expressions.

Simply

1. Create a directory in the Products directory of your Zope instance

2. Put the code below in a file called 'RegexField.py' in that directory.

3. Create a file called '__init__.py' with the following line::

import RegexField

4. Create a RegexField.gif in that directory as well. Take whatever icon you like :)

5. Done!


Source (Text):
#
# RegexField for Formulator
#
# Copyright (c) 2003 Philipp von Weitershausen
#                    <philipp@weitershausen.de>
#

import os, re
from Products.Formulator.DummyField import fields
from Products.Formulator.Field import ZMIField
from Products.Formulator.FieldRegistry import FieldRegistry
from Products.Formulator.Validator import StringBaseValidator
from Products.Formulator import Widget

class RegexValidator(StringBaseValidator):

    property_names = StringBaseValidator.property_names + \
                     ['regex']

    regex = fields.StringField(
        'regex',
        title="Regular Expression",
        required=1,
        default="",
        description="Enter a regular expression here"
        )

    message_names = StringBaseValidator.message_names + \
                    ['regex_not_matched']

    regex_not_matched = "The entered value did not match the regular " \
                          "expression."

    def validate(self, field, key, REQUEST):
        value = REQUEST.get(key, "")
        srematch = re.match(field.get_value('regex'), value)
        if srematch is None:
            self.raise_error('regex_not_matched', field)
        return value

RegexValidatorInstance = RegexValidator()

class RegexField(ZMIField):
    meta_type = "RegexField"

    widget = Widget.TextWidgetInstance
    validator = RegexValidatorInstance

path = os.path.dirname(__file__)
iconpath = os.path.join(path, "RegexField.gif")
FieldRegistry.registerField(RegexField, icon=iconpath)

Comments:

Required? by halber_mensch - 2005-07-15
This validator does not check the field value 'required' to ensure that empty strings on non-required fields are accepted.

From the standard validators, this base case is accounted for:

        value = StringValidator.validate(self, field, key, REQUEST)
        if value == "" and not field.get_value('required'):
            return value

The RegexValidator inherits the StringBaseValidator, so we need to change this slightly:

        value = StringBaseValidator.validate(self, field, key, REQUEST)
        if value == "" and not field.get_value('required'):
            return value