简体   繁体   English

如何在Ajax验证中使用WTForms?

[英]How to use WTForms in Ajax validation?

I accustomed of using WTForms by means of Flask-WTF in my flask application. 我习惯于在我的烧瓶应用程序中使用Flask-WTF使用WTForms。 Doing server side validation is trivial. 进行服务器端验证是微不足道的。 But how do I leverage this server validation to become a field level, ajax, client side validation? 但是,如何利用此服务器验证成为字段级别,ajax,客户端验证? 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. 在客户端,您将处理程序附加到窗体中所有控件中的blur事件。

  • 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. 每次发生模糊事件时,您都会运行一个Javascript函数来收集所有字段的值,然后将它们作为ajax POST请求提交。

  • On the server the view function that handles this ajax POST request instantiates the Flask-WTF form and then validates it. 在服务器上,处理此ajax POST请求的视图函数实例化Flask-WTF表单,然后验证它。 Any errors that resulted from validation are collected into a dictionary that is then sent in a JSON response back to the client. 验证产生的任何错误都会收集到字典中,然后通过JSON响应发送回客户端。

    For example, a successful validation could return the following JSON: 例如,成功验证可以返回以下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. 客户端获取此JSON响应并将所需的更改应用于DOM以公开错误。

  • 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. 如果在前一个返回之前得到一个新的模糊事件,您可能希望中止待处理的ajax POST并启动一个带有更新字段值的新事件。 You should have only one pending validation request at a time to avoid race conditions. 您应该一次只有一个待处理的验证请求,以避免竞争条件。

A great question. 一个很好的问题。 This is what we do (flask backend, jquery frontend): 这就是我们做的事情(烧瓶后端,jquery前端):

  • use jquery.forms plugin to ajax forms. 使用jquery.forms插件到ajax表单。 Pretty solid mature code. 非常扎实的成熟代码。 Shortcoming, cannot send json encoded data, only form-urlencoded. 缺点是,无法发送json编码数据,只能形成urlencoded。 Receives plain or json data. 接收普通或json数据。
  • use wtfroms for form validation. 使用wtfroms进行表单验证。 Very mature codebase. 非常成熟的代码库。
  • tried to use wtforms-json for accepting json, very screwy problems. 试图使用wtforms-json接受json,非常棘手的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM