On 12/03/2006, at 0:03, Robin Haswell wrote:
>
> Ah thanks, I think Python has a little more magic in it than I
> realised :-) I've only been doing
> python got about 100 hours now, so I'm still a relative beginner -
> in terms of language capabilities
> that is :-)
>
> One last question though (promise), is it possible to implement a
> custom validator - for example, to
> match a regular expression or to check if a value is not already in
> a database? Or maybe taking a
> more robust tact, is it possible to raise an error on an input
> value while a controllermethod is
> running? That might be a much better option as I can foresee some
> situations where I only know that
> some input is not acceptable after doing a fair amount of input. I
> know I could just flash() a
> message but having the message appear next to the field would be a
> lot better.
Sure, take a look at FormEncode's docs. Widget validators are nothing
fancier than that...
For expample:
v = validator.Regex(....)
would be your regex validator. If you need a more complex validator
you can always subclass validators.FancyValidator, example:
from turbogears.validators import FancyValidator, Invalid
from model import User
class UserValidator(FancyValidator):
messages = {
'user_exists' : 'Theres a user already with that name',
}
def to_python(self, value, state=None):
try:
User.byUserId(value)
# If no exception is raised it means the user is in
database so
# we raise an Invalid to signal validation error
raise Invalid(message('user_exists', state), value, state)
except LookupError:
# good, user is not in DB
pass
return value
This will check if a user with that username is in the database.
validators can be really simple to create, basically the only methods
you need to care about is to_python and from_python which do the
translation back and forth python/web raising Invalid exceptions when
the input is not valid.
What I would recommend is that all validation should be done at
validators, this makes your controllers more readable as you already
know the input is valid when it reaches your code (If the validators
have no bugs that is)
>
Alberto
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"TurboGears" 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/turbogears
-~----------~----~----~----~------~----~------~--~---