我一直在尝试使用 JavaScript 来仅验证字段中的数字。 但是不工作
这里是 JavaScript 代码:
<script language="JavaScript">
function onlyNumbers(evt)
{
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
这里是我在 Flask 中使用的 WTForms:
{{ form.saturacion.label(class="form-control-label") }}
{% if form.saturacion.errors %}
{{ form.saturacion(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.saturacion.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.saturacion(class="form-control form-control-lg") }}
{% endif %}
这两个在html文件中
这里我有表格:
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField, SelectField,RadioField,IntegerField
from wtforms.validators import DataRequired,Length, Email, EqualTo,ValidationError,InputRequired
from init.models import User
class PredictionForm(FlaskForm):
saturacion = IntegerField('Saturacion de O2', validators=[InputRequired(), Length(min=1, max=2)])
有人可以告诉我如何使用 WTForms 只允许该字段中的数字吗?
最佳答案
wtforms native IntegerField
(使用 from wtforms import IntegerField
导入)呈现文本输入:
class IntegerField(Field):
"""
A text field, except all input is coerced to an integer. Erroneous input
is ignored and will not be accepted as a value.
"""
widget = widgets.TextInput()
如果您导入 native HTML5 输入(from wtforms.fields.html5 import IntegerField
),则验证由您的浏览器执行而不需要 JS,因为表单输入是不同的类型:
class IntegerField(core.IntegerField):
"""
Represents an ``<input type="number">``.
"""
widget = widgets.NumberInput(step='1')
通过阅读您的 JS,我看不到您在任何地方 Hook 到表单提交过程以阻止它或通过它,而且我也看不到您如何将您的函数 Hook 到特定的表单输入。
关于javascript - 将 JavaScript 与 WTForms 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53382619/