WTForms Regexp验证器:如何使用正则表达式匹配html标记内的空白 [英] WTForms Regexp validator: How to match white space within html tags using regex

查看:188
本文介绍了WTForms Regexp验证器:如何使用正则表达式匹配html标记内的空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有textarea字段的表单,想知道当textarea仅包含空格时,是否可以使用WTForms Regexp验证程序阻止表单提交. 有办法吗?

I have a form with a textarea field and wonder if I could use WTForms Regexp validator to prevent the form submitting when the textarea contains only blank spaces. Is there a way?

这是我的表格:

class AddReviewForm(FlaskForm):
    review = TextAreaField("Review", validators=[DataRequired())
    submit = SubmitField("Post Review")

我希望Regexp将允许我仅防止空格. 我的textarea字段包括CKEditor,它将<p>(或其他标签)添加到输入中,以将其显示为所见即所得.

I was hoping Regexp would allow me to prevent only spaces. My textarea fields include CKEditor, which adds <p> (or other tags) to the input in order to display it as WYSIWYG.

因此在数据库中,空格看起来像这样:

So in the database the whitespaces look like this:

"<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</p>"

那不应该验证.

推荐答案

您可以创建自定义验证器.

You can create a custom validator.

导入ValidationError:

from wtforms import ValidationError

自定义验证器:

def validate_review(self, field):
    text = field.data.replace('<p>','')
                     .replace('</p>','')
                     .replace('&nbsp;','')
                     .replace('&ensp;','')
                     .replace('&emsp;','')
                     .replace('<br>','')
    if not text:
        raise ValidationError('This field should not contain only white spaces')

请确保此自定义验证器是AddReviewForm类的方法.另请注意,自定义验证器的方法名称应采用validate_<field_name>的形式.

Make sure that, this custom validator is method of AddReviewForm class. Also note that, the custom validator's method name should be in the form of validate_<field_name>.

这篇关于WTForms Regexp验证器:如何使用正则表达式匹配html标记内的空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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