0

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

NrNazifi
  • 1,621
  • 3
  • 25
  • 36

1 Answers1

1

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()('someone@example.com')

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&value=someone@example.com.

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.

Community
  • 1
  • 1
Anthony
  • 25,466
  • 3
  • 28
  • 57
  • thanks @Anthony. but I have a form and I wanna check validation of its fields in client-side. I wrote a webMethod and send filed's value to it with ajax. Now, how can I use validators? Do you have a recommend for me? – NrNazifi Mar 12 '13 at 09:06