Re: [FE-discuss] using min and max with float

Top Page
Author: Shannon -jj Behrens
Date:  
To: formencode-discuss
Subject: Re: [FE-discuss] using min and max with float
Here's one approach to adding a range validator:

import formencode
from formencode import validators

__docformat__ = "restructuredtext"


class Range(formencode.FancyValidator):

    """Ensure that an int or float value is in range.

    Example::

        >>> validator = formencode.All(validators.Int(),
        ...                            Range(min=0, max=10))
        >>> validator.to_python('5')
        5
        >>> validator.to_python("ten")
        Traceback (most recent call last):
            ...
        Invalid: Please enter a number: ten
        >>> validator.to_python('-1')
        Traceback (most recent call last):
            ...
        Invalid: Please enter a value that is 0 or greater
        >>> validator.to_python('11')
        Traceback (most recent call last):
            ...
        Invalid: Please enter a value that is 10 or smaller

    """

    messages = {
        'tooLow': "Please enter a value that is %(min)s or greater",
        'tooHigh': "Please enter a value that is %(max)s or smaller",
        'notCastable': "Please enter a number: %(value)s"
    }

    min = None
    max = None

    def __initargs__(self, args):
        if self.min != None:
            self.min = self.min
        if self.max != None:
            self.max = self.max

    def cast(self, value, state):
        try:
            return float(value)
        except ValueError, e:
            msg = self.message("notCastable", state, value=value)
            raise formencode.Invalid(msg, value, state)

    def validate_python(self, value, state):
        if (self.min != None and
            self.cast(value, state) < self.cast(self.min, state)):
            msg = self.message("tooLow", state, min=self.min)
            raise formencode.Invalid(msg, value, state)
        if (self.max != None and
            self.cast(value, state) > self.cast(self.max, state)):
            msg = self.message("tooHigh", state, max=self.max)
            raise formencode.Invalid(msg, value, state)

-------------------------------------------------------------------------
This SF.net email is sponsored by the 2008 JavaOne(SM) Conference
Don't miss this year's exciting event. There's still time to save $100.
Use priority code J8TL2D2.
http://ad.doubleclick.net/clk;198757673;13503038;p?http://java.sun.com/javaone
_______________________________________________
FormEncode-discuss mailing list
FormEncode-discuss@???
https://lists.sourceforge.net/lists/listinfo/formencode-discuss