python - 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> </p>"
And that shouldn't validate.
解决方案
您可以创建自定义验证器。
进口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>
.