On Jan 15, 2006, at 1:57 PM, Clark Evans wrote:
I have field validation code that currently is simple regex that I can
run both in javascript on the browser, and in python code on the
server. This has been working well. However, recently I've been adding
data types that are a bit more complicated, and multi-input-field data
types that have an overall validity check. This doesn't work as
nicely with regular expressions -- but I'd like to keep my dual
client/server side checking. The two obvious solutions is to either
(a) duplicate your code in both javascript and python, or (b) write
your validation code in javascript and exec to spidermonkey. Neither
are great options.
It seems to me that this, i.e. form validation, is really the only use
case worth pursuing for such py->js functionality. And, instead of
attacking generic py->js conversion, with all the problems as pointed
out already, it may be more reasonable to just address this use case
specifically. I mean, would it not be easier to just use a good
validation library in python, replicate that functionality in
javascript, and then have your form generating/handling framework to
generate the glue js code along with the html to do the desired
client-side checking calls, along with of course the python calls on
the server. I.e. specify your form declaratively, and then have it
validated automatically both on client and on server, using equivalent
but manually produced validation libraries for each end.
Another point is that the type you want to check for on the client may
be different than on the server! E.g. a text and numeric input on the
client may be tested as an already digested custom instance on the
server. Plus, this relieves the necessity for a multitude of check
callbacks to the server, should the client form implement checking in
that way.
At this point I can't help mentioning this really nice generic
validation module, spec.py, that is included in qp [1]. It allows you
to specify data types of arbitrary complexity, with amazing
expressivity, and automates the checking accordingly. It also builds on
the types already available in python. Data specs can be simple, for
example (using '_is' suffix convention to denote the type we want to
constrain on the attribute):
a_str_is = str
a_some_str_or_unicode_is = string
an_email_is = pattern('[EMAIL PROTECTED],3}$')
a_string_or_int_is = either(string,int)
a_list_of_int_is = [int]
a_dict_strkeys_myclassvals_is = {str:instance('MyClass')}
and so on. It is really worth a look... I have not invested any thought
whether such a validation lib could be possible in js, but if it were
that would be a really wonderful thing. Would such a lib be
implementable in js?
mario
[1] http://www.mems-exchange.org/software/qp/
Spec module is in qp.lib.spec, but has no dependency on the rest of the
package.