WTForms Regexp验证器:如何使用正则表达式匹配html标记内的空白 [英] WTForms Regexp validator: How to match white space within html tags using regex
问题描述
我有一个带有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> </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(' ','')
.replace(' ','')
.replace(' ','')
.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屋!