Am 17.11.2005 um 10:07 schrieb Simon Willison:
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.
While there are definitely many types of validations that can't be
performed on the client side, calling back to the server just to
check whether e.g. a text-input is empty is overkill IMO. The same
goes for validity checks for common things like text fields expecting
an email address or date.
I'd prefer a hybrid approach, where simple javascript validation
checks are generated, and the others are performed via AJAX callbacks.
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.
Validation starts to get interesting when it involves relations
between multiple field, for example one field must be non-empty and
contain a date, but only if some checkbox is checked. It'd be
interesting if such relations could somehow be expressed, so that the
server callback would get all the data it needs for the validation,
and not more.
OTOH, the validation in this example would ideally not even get
triggered, because the date text field would be disabled until the
checkbox got checked :-P A better example is probably the classic
"matching passwords" validation.
Cheers,
Chris
--
Christopher Lenz
cmlenz at gmx.de
http://www.cmlenz.net/