user350540
user350540

Reputation: 469

Validate WTF Flask Form Input Values

I have the following form in my flask app. I'd like to ensure that the input value is actually an integer and also if the value entered in token > k here k can be some number it spits an error message to the screen. The IntegerField doesn't seem to enforce integer values, e.g., if the user enters 2.3 it passes that to my function which fails because it expects an integer.

Can this type of error message happen in the form or do I need to program that inside my flask app once the value is passed from the form to the server?

class Form(FlaskForm):
    token = IntegerField('Token Size', [DataRequired()], default = 2)          
    submit = SubmitField('Submit')

EDIT Per the comment below, updating this with my revised Form and the route

class Form(FlaskForm):
    token = IntegerField('Token Size', validators=[DataRequired(), NumberRange(min=1, max=10, message='Something')], default = 2)
    ngram_method = SelectField('Method', [DataRequired()],
        choices=[('sliding', 'Sliding Window Method'),
                 ('adjacent', 'Adjacent Text Method')]) 
    rem_stop = BooleanField('Remove Stop Words', render_kw={'checked': True})
    rem_punc = BooleanField('Remove Punctuation', default = True)
    text2use = SelectField('Text To Use for Word Tree', [DataRequired()],
        choices=[('clean', 'Clean/Processed Text'),
                 ('original', 'Original Text String')])
    pivot_word = TextField('Pivot Word for Word Tree', [DataRequired()])                
    submit = SubmitField('Submit')

And the route in which the form is used

@word_analyzer.route('/text', methods=('GET', 'POST'))
def text_analysis():
    form = Form()
    result = '<table></table>' 
    ngrams = '<table></table>' 
    orig_text = '<table></table>' 
    text = ""
    if request.method == 'POST':
        tmp_filename = tempfile.gettempdir()+'\\input.txt'
        if request.files:
            txt_upload = request.files.get('text_file')
            if txt_upload:
                f = request.files['text_file']
                f.save(tmp_filename)
        if os.path.exists(tmp_filename):
            file = open(tmp_filename, 'r', encoding="utf8") 
            theText = [line.rstrip('\n') for line in file]
            theText = str(theText)
            token_size = form.token.data
            stops = form.rem_stop.data
            punc = form.rem_punc.data
            ngram_method = form.ngram_method.data
            text_result = text_analyzer(theText, token_size = token_size, remove_stop = stops, remove_punctuation = punc, method = ngram_method)
            result = pd.DataFrame.from_dict(text_result, orient='index', columns = ['Results'])[:-3].to_html(classes='table table-striped table-hover', header = "true", justify = "center")
            ngrams = pd.DataFrame.from_dict(text_result['ngrams'], orient='index', columns = ['Frequency']).to_html(classes='table table-striped table-hover', header = "true", justify = "center")
            if form.pivot_word.data == None:
                top_word = json.dumps(text_result['Top Word'])
            else:
                top_word = json.dumps(form.pivot_word.data)
            if form.text2use.data == 'original':
                text = json.dumps(text_result['original_text'])
            else:
                text = json.dumps(text_result['clean_text'])
            if form.validate_on_submit():   
                return render_template('text.html', results = [result], ngrams = [ngrams], form = form, text=text, top_word = top_word) 
    return render_template('text.html', form = form, results = [result],ngrams = [ngrams], text=text, top_word='') 

Upvotes: 1

Views: 2295

Answers (1)

avizzzy
avizzzy

Reputation: 535

Use the NumberRange validator from wtforms.validators.NumberRange. You can pass an optional Min and Max value along with the error message. More info here

Update

# Form Class
class Form(FlaskForm):
    token = FloatField('Token Size', validators=[DataRequired(), NumberRange(min=1, max=10, message='Something')])

# Route
if form.validate_on_submit():
    print(form.name.data)

Here is an example that should work, make sure your form class field looks similar and also that in your route you use form.validate_on_submit():.

Upvotes: 1

Related Questions