How to use WTForms in Ajax validation?

空扰寡人 提交于 2019-12-17 22:35:57

问题


I accustomed of using WTForms by means of Flask-WTF in my flask application. Doing server side validation is trivial. But how do I leverage this server validation to become a field level, ajax, client side validation? So, when user tab to another input fields, my application can directly goes on validating it and give validation warning/info/error.

I haven't found a resource in the internet yet


回答1:


A possible solution is as follows:

  • On the client side you attach a handler to the blur event in all the controls in the form.

  • Each time the blur event occurs you run a Javascript function that collects the values of all the fields and then submits them as an ajax POST request.

  • On the server the view function that handles this ajax POST request instantiates the Flask-WTF form and then validates it. Any errors that resulted from validation are collected into a dictionary that is then sent in a JSON response back to the client.

    For example, a successful validation could return the following JSON:

    { 
        "errors": {}
    }
    

    A response that includes errors could be:

    {
        "errors": { 
            "name": "This field is required",
            "age": "Enter a numeric value between 0 and 99"
        }
    }
    
  • The client gets this JSON response and applies the required changes to the DOM to expose the errors.

  • If you get a new blur event before the previous one returned you will probably want to abort the pending ajax POST and start a new one with updated field values. You should have only one pending validation request at a time to avoid race conditions.




回答2:


A great question. This is what we do (flask backend, jquery frontend):

  • use jquery.forms plugin to ajax forms. Pretty solid mature code. Shortcoming, cannot send json encoded data, only form-urlencoded. Receives plain or json data.
  • use wtfroms for form validation. Very mature codebase.
  • tried to use wtforms-json for accepting json, very screwy problems.


来源:https://stackoverflow.com/questions/19898967/how-to-use-wtforms-in-ajax-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!