2008年6月27日金曜日

RangedInt Validator

このエントリーをブックマークに追加 このエントリーを含むはてなブックマーク
上限と下限をチェックできる整数値のValidatorを書いてみた。formencodeになんでないのかねぇ。
ひょっとして組み合わせて作れるのかな?しかしこの程度ならprimitiveとしてライブラリにあってもいい気がする。


82 class RangedInt(formencode.validators.Int):
83 """
84 Convert a value to an integer.
85
86 Example::
87
88 >>> Int.to_python('10')
89 10
90 >>> Int.to_python('ten')
91 Traceback (most recent call last):
92 ...
93 Invalid: Please enter an integer value
94 """
95 not_empty = True
96 min = None
97 max = None
98
99 messages = {
100 'integer': "Please enter an integer value",
101 'tooLarge': "Enter a value %(max)i or less",
102 'tooSmall': "Enter a value %(min)i or larger",
103 }
104
105 def _to_python(self, value, state):
106 try:
107 iv = int(value)
108 except (ValueError, TypeError):
109 raise Invalid(self.message('integer', state),
110 value, state)
111 if (self.max is not None and value is not None
112 and iv > self.max):
113 raise Invalid(self.message('tooLarge', state,
114 max=self.max),
115 value, state)
116 if (self.min is not Nonejavascript:void(0)
117 and (not value or iv < self.min)):
118 raise Invalid(self.message('tooSmall', state,
119 min=self.min),
120 value, state)
121 return iv
122
123 _from_python = _to_python