WTForms无法验证NumberRange [英] WTForms not validating NumberRange
问题描述
我正在制作一个将小数作为输入的WTForm,并且我试图将输入限制为一定范围的数字(介于0和10之间(包括0和10之间)).但是,验证器NumberRange
似乎没有任何作用.
I'm making a WTForm which takes Decimals as inputs, and I'm trying to restrict input to a range of numbers (between 0 and 10 inclusive). However, the validator NumberRange
doesn't seem to do anything.
Python(使用烧瓶):
Python (using flask):
from flask import render_template
from flask_wtf import FlaskForm
from wtforms import DecimalField, SubmitField, validators
class NumberForm(FlaskForm):
question = DecimalField('Question 1',
[validators.NumberRange(min=0, max=10, message="blah"),
validators.Optional()])
submit = SubmitField('Submit')
@app.route('some_route/', methods=['GET', 'POST])
def page():
form = NumberForm()
if form.validate_on_submit():
return some_success_or_other
return render_template('page.html', form=form)
HTML:
<form method="POST">
<div class="form-group-row">
{{ form.hidden_tag() }}
{{ form.question.label }}
<div>
{{ form.question }}
</div>
</div>
<div class="form-group-row">
{{ form.submit }}
</div>
</form>
无论我输入什么值,都会提交question
字段.我认为它不允许文本,也不允许负数,也不允许范围之外的数字(例如10000).
The question
field will be submitted whatever value I input. I thought it wouldn't allow text, nor would it allow negative numbers, nor numbers outside the range (e.g. 10000).
我尝试将NumberRange
的最小值和最大值更改为0.0
和10.0
.我试过取出消息参数.我试过取出Optional
验证器.但是这些都不能阻止我在表格中输入超出范围的数字.
I've tried changing the NumberRange
min and max to 0.0
and 10.0
. I've tried taking out the message arguments. I've tried taking out the Optional
validator. But none of these prevents me entering out of range numbers in the form.
(当我将Optional
替换为DataRequired
时,除非字段中有数据,否则表单不会提交,因此验证程序至少会起作用.)
(When I replaced Optional
with DataRequired
, the form would not submit unless there was data in the field, so that validator worked at least.)
有人知道我在做什么错吗?
Anyone know what I'm doing wrong?
看来问题已分为两部分:不进行验证,并且验证消息不闪烁.下面的答案解决了缺乏验证的问题.
it seems the problem was split into two parts: no validation, and validation messages not flashing. The answer below fixes the lack of validation.
推荐答案
显然您的应用程序配置不正确.代码应如下所示:
Apparently your application is not correctly configured. The code should look like this:
from flask_wtf import FlaskForm
from wtforms import SubmitField, DecimalField
from wtforms.validators import NumberRange
class NumberForm(FlaskForm):
question = DecimalField('Question 1', validators=[NumberRange(min=0, max=10, message='bla')])
submit = SubmitField('Submit')
这篇关于WTForms无法验证NumberRange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!