[Zope3-Users] Invariants and forms

Maciej Wisniowski maciej.wisniowski at coig.katowice.pl
Mon Aug 13 16:41:15 EDT 2007


> I've found two different examples(see below), but both don't display my given exception message. The only thing i get is the standard error message.
What do you mean by standard error message?


> Second example
> (taken from:
> http://blog.gocept.com/zope3-testen-von-felderuebergreifenden-bedingungen-invariants-in-interfaces-mit-zope-formlib-aktualisiert)
> 
> import zope.interface
> 
> class IUser(zope.interface.Interface):
>     password = zope.schema.Password(title=u"Passwort")
>     password2 = zope.schema.Password(title=u"Wiederholung des Passworts")
> 
>     @zope.interface.invariant
>     def arePasswordsEqual(user):
>         if user.password != user.password2:
>             raise zope.interface.Invalid(
>                 u"""Das Passwort und die Wiederholung sind nicht gleich.""")

I think this should work.
Take a look at formlib/form.txt  - section about Invariants. If
it doesn't then I think your error is from somewhere else (again - what
is standard error message for you?)

There is also another possibility to do some checks between distinct
fields. To do this, in your action handler you may do your check
using values from 'data' dictionary, and if there is error you should
set:

self.form_reset = True
self.errors.append(u'your error message')


If you want to use this kind of validation (at action handler) to set
error messages for specific field you may do this either. I've added
function to my Form class for this:


from zope.app.form.interfaces import WidgetInputError
(...)
    def setWidgetError(self, name, v):
        """ Helper function for validation purposes.
            Sets error for widget
             @name - field name
             @v - error message
        """
        w = self.widgets.get(name)
        if w:
            w._error = WidgetInputError(
              self.context.__name__, w.label, v)
        return w._error


In this case, if you validate your values in action handler you may do:


self.setWidgetError('password_confirmation',
                    u'Confirmation doesn\'t match')
self.form_reset = True


and error message will be bound to 'password_confirmation' field.


-- 
Maciej Wisniowski


More information about the Zope3-users mailing list