On 17 Nov 2005, at 05:48, David Ascher wrote:

Goofy idea: use the Python logic to generate JS code to do clientside validation based on the model-specified constraints. Detailed specification and implementation are left as an exercise to the reader. ;-)

Here's a concept for form validation with Ajax I've been knocking around for ages that I would love to see in Django.

The most annoying thing about client-side validation is having to duplicate the logic used in your server-side validation code. Automating this is a nice idea but suffers from a couple of pretty big problems:

1. Differences between JavaScript and Python regular expression syntax
2. Some checks, such as "is this user name already taken", can only happen with server involvement

Here's how to fix both of these: have the client-side validation run against the server-side validation logic using Ajax to communicate between the two.

Say you have a form that submits to here:

/add-blog-entry/submit/

First, add another end point:

/add-blog-entry/validate/ (or validate_json or whatever)

Associate a pre-written (generic?) view with that end point that is itself associated with a set of validation rules - in Django terms that would probably be a manipulator of some sort. Every time a form field is filled in the blur event causes JS to post the field name and the data from that field at the validate endpoint. It returns a simple JSON object representing if the data was valid, invalid or undetermined (for fields which can't be validated without seeing information from elsewhere in the form - we probably don't want to send all form field data at once for every validation call as forms involving big textareas can end up with a lot of data in them). Invalid responses are accompanied by a JSON array of human readable error messages.

JavaScript code on the client can then add green ticks or red crosses to fields indicating valid and invalid data.

Cheers,

Simon

Reply via email to