Re: Partial validation results from an invalid input?

Chris Lambacher <[email protected]> Mon, 26 Dec 2011 19:53:03 -0500
Newsgroups gmane.comp.python.formencode
Message-ID <CAAXXHgL+aSWLxO4CdbrC3WxpwrGWZcrxwqjqMbj1_wO05TjoYA@mail.gmail.com>
On Mon, Dec 26, 2011 at 6:40 PM, Daniel Lepage <[email protected]> wrote:
> Hi Chris,
>
> This is done through AJAX. I don't have the "enter values, then hit
> save" workflow - instead, the user can change the values in these form
> fields at any time and the results are immediately sent to the server
> and, if valid, saved.

It is not common to save *some* of the data (i.e. the parts that
validated) rather than *all* the data (i.e. on completely valid). I
think as a user, in most cases, I would find this surprising
behaviour.

>
> The values are used by other parts of the system, so I can't just
> store the POSTed strings - I need the actual converted values for all
> the valid POSTed values, even if there are also invalid values.

You certainly don't want to use the raw posted values in general for
anything other than re-generating forms. ToscaWidgets *should* be
capable of regenerating forms on error (I haven't looked at
ToscaWidgets in a long time and not very closely either).

If you are doing an AJAX Post, then you should also be able to return
success or failure back to the form (including information about which
fields failed) and leave the content of the page untouched unless you
see that the validation completed because the server gave you a
successful result.

If you *really* want to collect partial success and the errors, you
should probably eschew Schemas and write a function which takes a dict
of validators and returns the errors and the valid values. This is
fairly trivial to write:

def validate_things(validators, form_values):
    valid = {}
    errors = {}
    for key, validator in validators.iteritems():
        try:
             valid[key] = validator.to_python(form_values.get(key))
        except Invalid, e:
             errors[key] = e
     return valid, errors

-Chris

-- 
Christopher Lambacher
[email protected]

------------------------------------------------------------------------------
Write once. Port to many.
Get the SDK and tools to simplify cross-platform app development. Create 
new or port existing apps to sell to consumers worldwide. Explore the 
Intel AppUpSM program developer opportunity. appdeveloper.intel.com/join
http://p.sf.net/sfu/intel-appdev