首页 > 解决方案 > WTForms Regexp validator: How to match white space within html tags using regex

问题描述

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?

This is my form:

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

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>"

And that shouldn't validate.

标签: pythonregexflaskflask-wtforms

解决方案


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

进口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>.


推荐阅读