On Tue, Mar 2, 2010 at 3:20 AM, Mark <[email protected]> wrote:
> Hi guys,
>
> Which validator should I use for a select box, where the 'value' of
> the option selected is a number?
>
> For instance:
>
> <select name="type_id" id="type_id">
> <option value="6">A</option>
> <option value="7">B</option>
> <option selected="selected" value="2">C</option>
> </select>
>
> I am pulling the values to populate the select box from the database.
> Should I use OneOf or should I use Int?
I made a combined validator for that. Here it is, along with a couple
other useful validators.
===
import formencode.validators as v
class SelectInt(v.FancyValidator):
"""A combination of the Int and OneOf validators with a custom message"""
__unpackargs__ = ("list",)
not_empty = True
def _to_python(self, value, state):
try:
return int(value)
except ValueError:
self._invalid(value, state)
_from_python = _to_python
def validate_python(self, value, state):
if value not in self.list:
self._invalid(value, state)
def _invalid(self, value, state):
message = "please choose an item from the list"
raise v.Invalid(message, value, state)
===
By the way, a couple other validators I find useful:
===
# For checkboxes
class Boolean(v.StringBoolean):
if_missing = False
# For integer fields
class Int(v.Int):
messages = {
"integer": _("Please enter a numeric value"),
}
===
> What about multi-select boxes? Should those also use the same
> validator as select boxes like above?
I'm not sure about that. It would probably be best to ask on the
FormEncode list. FormEncode has a few ways to handle multiple values,
and I'm not sure which one would be appropriate for a multiselect.
--
Mike Orr <[email protected]>
--
You received this message because you are subscribed to the Google Groups
"pylons-discuss" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/pylons-discuss?hl=en.