如何在Ajax验证中使用WTForms? [英] How to use WTForms in Ajax validation?

查看:231
本文介绍了如何在Ajax验证中使用WTForms?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯于在烧瓶应用程序中使用Flask-WTF来使用WTForms。做服务器端验证是微不足道的。但是,我怎么利用这个服务器验证成为一个字段级别,Ajax,客户端验证?所以,当用户选项卡到另一个输入字段,我的应用程序可以直接进行验证,并给出验证警告/信息/错误。

我还没有找到资源互联网还有一个可能的解决方案如下:

    解决方案
  • 在客户端,您将一个处理程序附加到表单中所有控件的 blur 事件中。


  • 每次发生模糊事件时,您都会运行一个JavaScript函数,收集所有字段的值,然后将其作为ajax POST请求提交。

  • $ b
  • 在服务器上,处理这个ajax POST请求的view函数实例化Flask-WTF表单,然后验证它。任何由验证产生的错误都会被收集到一个字典中,然后通过JSON响应发送给客户端。

    例如,成功的验证可能会返回以下JSON:

    $ p $ {
    errors:{}
    }

    错误可能是:

      {
    errors:{
    name:This field is所需的,
    age:输入介于0和99之间的数字
    }
    }


  • 客户端获取此JSON响应,并将所需的更改应用于DOM以显示错误。

  • 如果在前一个返回之前得到一个新的模糊事件,您可能会想要中止挂起的ajax POST,并使用更新的字段值开始一个新的。您应该一次只有一个挂起的验证请求,以避免竞争条件。

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

解决方案

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.

这篇关于如何在Ajax验证中使用WTForms?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆