1

I've been trying to use JavaScript to validate only numbers in a field. But isn't working

Here I have the JavaScript code:

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

and here I have the WTForms that I am using with Flask:

{{ 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 %} 

These two are in the html file

And here I have the form:

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)]) 

Could someone please tell me how to allow only numbers in that field with WTForms?

1 Answer 1

1

wtforms native IntegerField (imported with from wtforms import IntegerField) renders a text input:

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() 

If you import the native HTML5 input (from wtforms.fields.html5 import IntegerField) then the validation is performed by your browser without the need for JS since the form input is of a different type:

class IntegerField(core.IntegerField): """ Represents an ``<input type="number">``. """ widget = widgets.NumberInput(step='1') 

From reading your JS I can't see anywhere where you hook into the form submission process to prevent it or pass it through, and also I can't see how you are hooking your function to the specific form input.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank so much! It worked perfectly! Do you think that using NumberRange(min=0, max=100) is a good idea to control the range of numbers of the input?
The basic principle of web design form input validation is that you do it both on server side and on client side. If you want to restrict your users to only integers between 0 and 100 then apply that validator rule in your python code and also add it as an option on the HTML5 input form, which does permit this simple min-max validation. That way you are covered for both cases.