问题
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.
回答1:
You can create a custom validator.
Import ValidationError
:
from wtforms import ValidationError
Custom validator:
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')
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>
.
回答2:
Take a look at this I think this might help you :
Here is the link to the above image
As you can see from the image above this should satisfy your condition :
"if the data is a string type, a string containing only whitespace characters is considered false."
Let me know if that works :D!
来源:https://stackoverflow.com/questions/62092819/wtforms-regexp-validator-how-to-match-white-space-within-html-tags-using-regex