[英]How to encode regex pattern for valid json and html5 for form validation?
I work on improving the validation of form configurations that are saved in a python flask app.我致力于改进保存在 python flask 应用程序中的表单配置的验证。 The form config comes in via an API in json. A user can save a regex pattern for their form field to have additional validation.
表单配置通过 json 中的 API 输入。用户可以为其表单字段保存正则表达式模式以进行额外验证。 Since I also wanted to prevent per default the submission of anything like an url in normal text fields (like First name, last name, etc.) I added a marshmallow regex pattern validation for all text fields:
^((?:\.\/\/).)*$
由于我还想防止默认情况下在普通文本字段(如名字、姓氏等)中提交任何类似 url 的内容,我为所有文本字段添加了棉花糖正则表达式模式验证:
^((?:\.\/\/).)*$
I also wanted a matching regex pattern on the frontend, where the form config is rendered into an actual html form.我还希望前端有一个匹配的正则表达式模式,其中表单配置呈现为实际的 html 表单。 This is done by a small petite-vue app that provides the html templates for form fields and automatically adds the pattern from the json config file to the html.
这是通过一个小型 petite-vue 应用程序完成的,该应用程序为表单字段提供 html 模板,并自动将模式从 json 配置文件添加到 html。
I noticed:我注意到:
Seems the backward slashes \ are a problem for json.似乎反斜杠 \ 是 json 的问题。
The slashes seem to be an issue here as well.斜线似乎也是这里的一个问题。
I already found out I can:我已经发现我可以:
But now I'm stuck on deciding which potential solution is the more robust choice, and which of the two apps is the place to implement it.但现在我一直在决定哪种潜在解决方案是更可靠的选择,以及这两个应用程序中的哪一个是实施它的地方。
So I need help deciding:所以我需要帮助决定:
I'll answer my own question.我会回答我自己的问题。 I understand now why it is unclear and not reproducable.
我现在明白为什么它不清楚且不可重现。 Hopefully an answer is still valuable.
希望答案仍然有价值。
tldr; tldr; The pattern is not right.
图案不对。 You don't need to escape the "/" or the ":".
您不需要转义“/”或“:”。
Long version长版
In the app flow, the pattern gets saved via python in a json file (ie. it uses json_dumps() and already gets encoded).在应用程序流程中,模式通过 python 保存在 json 文件中(即它使用 json_dumps() 并且已经编码)。 In my test case I just copy/pasted the pattern into the json file, resulting in not valid json. When escaping the \ manually, I either got an error on "invalid identity escape" or the pattern wouldn't match.
在我的测试用例中,我只是将模式复制/粘贴到 json 文件中,导致 json 无效。当 escaping 手动为 \ 时,我收到“无效身份转义”错误或模式不匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.