Adding 'smaller than' and 'bigger than' to Int validator

Jorge Godoy <[email protected]>
Newsgroups gmane.comp.python.formencode
Organization G2C Tech Consultoria Ltda.
Message-ID <[email protected]>
Hi!


I'd like to propose the following patch to the Int() validator so that we can
add limits to values passed in:


--------------------------------------------------------------------------------
Index: formencode/validators.py
===================================================================
--- formencode/validators.py    (revision 2035)
+++ formencode/validators.py    (working copy)
@@ -900,18 +900,44 @@
         Traceback (most recent call last):
             ...
         Invalid: Please enter an integer value
+        >>> iv = Int(smaller=3)
+        >>> iv.to_python('1')
+        1
+        >>> iv.to_python('5')
+        Traceback (most recent call last):
+            ...
+        Invalid: Please enter an integer smaller than 3
+        >>> iv = Int(bigger=3)
+        >>> iv.to_python('5')
+        5
+        >>> iv.to_python('1')
+        Traceback (most recent call last):
+            ...
+        Invalid: Please enter an integer bigger than 3
     """
 
+    smaller = None
+    bigger = None
+
     messages = {
         'integer': "Please enter an integer value",
+        'smaller': "Please enter an integer smaller than %(value)s",
+        'bigger': "Please enter an integer bigger than %(value)s",
         }
 
     def _to_python(self, value, state):
         try:
-            return int(value)
+            value = int(value)
         except (ValueError, TypeError):
             raise Invalid(self.message('integer', state),
                           value, state)
+        if self.smaller and value > self.smaller:
+            raise Invalid(self.message('smaller', state, value=self.smaller),
+                          value, state) 
+        if self.bigger and value < self.bigger:
+            raise Invalid(self.message('bigger', state, value=self.bigger),
+                          value, state) 
+        return value
 
     _from_python = _to_python
-------------------------------------------------------------------------------- 

The same approach could be done to the 'Number' validator, so that it gets
done for floats as well.


TIA,
-- 
Jorge Godoy      <[email protected]>


-------------------------------------------------------------------------
Using Tomcat but need to do more? Need to support web services, security?
Get stuff done quickly with pre-integrated technology to make your job easier
Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo
http://sel.as-us.falkag.net/sel?cmd=lnk&kid=120709&bid=263057&dat=121642
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.