z3c.formjs and AJAX validation

After some refactoring of the existing event hookup API, Stephan Richter and I implemented on the fly AJAX field validation. Here is how you would add validation to your form:


class ValidatorForm(layout.FormLayoutSupport,
                    jsvalidator.MessageValidator, form.Form):

    zope.interface.implements(interfaces.IAJAXValidator)

    @jsaction.handler(zope.schema.interfaces.IField, event=jsevent.CHANGE)
    def fieldValidator(self, event, selector):
        return self.ValidationScript(self, selector.widget).render()

So the steps are:

  1. Make your form subclass the MessageValidator class (or any other class that implements IAJAXValidator
  2. Implement the IAJAXValidator interface (the right methods and attributes are provided by MessageValidator
  3. Register the CHANGE event on all fields (or just the fields on which you want to have validation) using the handler decorator.
  4. Return the rendered ValidationScript (provided by MessageValidator superclass)
  5. All Done!

The MessageValidator class provides the validation script, which essentially renders a JavaScript function that acts as a callback for the AJAX request. This message validator modifies the DOM or does whatever else you want (probably something to alert the user that they have made a mistake). The MessageValidator class also provides a validate method, which can be accessed by traversing to the url, htp://host/path/to/your/@@form.html/validate. The validate method grabs the value of the field in question from the request, validates it using the regular form validation techniques, and sends back an error message (if validation failed).

You can check this out by looking at the z3c.formjsdemo package (on svn.zope.org).

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 76 other followers

%d bloggers like this: