NrNazifi
NrNazifi

Reputation: 1651

How to use validators in client side?

I wanna use web2py validators and my customize validators in client side with jquery! How to use them?

Upvotes: 0

Views: 488

Answers (1)

Anthony
Anthony

Reputation: 25536

web2py validators work on the server only. When a form is submitted, web2py does the validation on the server, and if there are any errors, it returns the form along with any error messages to be displayed. You may separately do client-side validation as well, but that will be independent of web2py's server-side validation.

UPDATE: If you want to send a value to the server via Ajax and use a validator to check it, you can call the validator directly. For example:

value, error = IS_EMAIL()('[email protected]')

All validators take a value and return a tuple when called, with the first element being the submitted value (or a transformation of it, depending on the validator), and the second element being either None if the validation passed or an error message if the validation failed.

A server-side validation action that accepts values via Ajax and returns either an error message or an 'OK' might look like this:

def validate():
    value, error = globals()[request.vars.validator]()(request.vars.value)
    return error if error else 'OK'

You can then make Ajax calls with URLs like:

/myapp/mycontroller/validate?validator=IS_EMAIL&[email protected].

However, it's not very efficient to send an Ajax request to validate each field separately, especially for validators that don't require any server-side processing. If you don't want the form submission to reload the page, another option is to put the form inside a web2py component, in which case the entire form submission and validation will be handled via Ajax automatically (in a single Ajax request).

If you really want to do client-side validation, then a better option is to use a client-side validation library.

Upvotes: 1

Related Questions