Flask form not displaying errors when I use custom validators

Flask form not displaying errors when I use custom validators



I'm creating custom validators for my Flask form inputs and as an example, I've defined a function below that checks whether you've included "s3://" in the input, and if not, I want it to throw an error.



When I test this out and omit the "s3://" in the input, no error is thrown. What am I doing wrong?



Form class:


from flask_wtf import FlaskForm
from wtforms import StringField, TextField, SubmitField, IntegerField, SelectField, validators
from wtforms.validators import ValidationError
import boto3

# CUSTOM VALIDATOR
def is_s3_uri(form, field):
if "s3://" not in field.data:
raise ValidationError('Bucket name must contain full path. Missing "s3://".')

class InputForm(FlaskForm):

input_uri = StringField('INPUT BUCKET', validators=[validators.required(), is_s3_uri])
output_uri = StringField('OUTPUT BUCKET', validators=[validators.required(), is_s3_uri])



HTML:


<div class="tab">
<h3>File Locations:</h3>
<div class="form-group required">
form.input_uri.label : form.input_uri(placeholder="(e.g. s3://pipeline-run/fastqs/)...", oninput=", this.className = ''")
</div>
% if form.input_uri.errors %
<ul class="errors">% for error in form.input_uri.errors %<li> error </li>% endfor %</ul>
% endif %
<div class="form-group required">
form.output_uri.label : form.output_uri(placeholder="(e.g. s3://pipeline-run/results/)...", oninput="this.className = ''")
</div>
% if form.input_uri.errors %
<ul class="errors">% for error in form.output_uri.errors %<li> error </li>% endfor %</ul>
% endif %
</div>



UPDATE:



I also tried adding a built-in validator (e.g. with Length(min=6, max=120)), but that doesn't get enforced either.


Length(min=6, max=120))


stack_name = StringField('STACK NAME', validators=[Length(min=4, max=120), DataRequired()])



UPDATE 2:


@app.route('/', methods=['GET', 'POST'])
def pipeline():

INPUT_URI = ''
OUTPUT_URI = ''

form = InputForm(request.form)

if request.method == 'POST':
if form.validate_on_submit():
INPUT_URI = request.form['input_uri']
OUTPUT_URI = request.form['output_uri']

# process info

else:
flash('Invalid params. Please re-try.', 'danger')
return redirect(request.path)

return render_template('pipeline-alt.html',
title='Pipeline Input',
form=form)



UPDATE 3:
Using the Jquery Form Validation Plugin



HTML:


<div class="form-group required">
form.input_uri.label : form.input_uri(placeholder="(e.g. s3://pipeline-run/fastqs/)...", oninput=", this.className = ''", name="input_uri")
</div>



JQuery:


<script>

$(document).ready(function ()

$('#regForm').validate( // initialize the plugin
rules:
input_uri:
required: true,
minlength: 4

,
submitHandler: function (form) // for demo
alert('valid form submitted'); // for demo
return false; // for demo

);

);

</script>



Result: TypeError: html_params() got multiple values for keyword argument 'name'


TypeError: html_params() got multiple values for keyword argument 'name'




1 Answer
1



Are you validating your form on submit? You didn't post enough code but I will try to help.



In the view that renders you should use form.validate_on_submit() in order for you form to get validated. I don't see your entire form code in the HTML you posted and if this is it, then you are missing a submit button that will send the form to the server for validation.


form.validate_on_submit()



Please post your view (that renders the form) code



Your form should use POST in the method for the example below.
An example of what your view that handles the form should llok like with form.validate_on_submit()


POST


form.validate_on_submit()


from flask import request
@app.route('/form_route', methods=['GET', 'POST'])
def form_route():
form = YourFormClass()
if request.method == 'POST':
if form.validate_on_submit():
# validation will be triggered from the if statement and if it validates, it will enter this if block
# perform actions if the form is valid
else:
# do somthing if the form is not valid
return render_template(form=form)






See my update 2 above. Even when adding the validate_on_submit(), I'm still getting the same problem. Also, this is a multi-page form, so I wanted incorrect inputs to show on the same page, not once I click "submit" on the final page. And there is indeed a submit button.

– claudiadast
Sep 7 '18 at 16:42



validate_on_submit()






In order for incorrect input errors to appear immediately without submitting the form, you have to use javascript. WTForms are rendered only on page load and there is no interaction with the server until you hit submit. You can use jQuery Validate which is widely used for client side validation. Using this jQuery plugin, you can achieve what you want jqueryvalidation.org

– shifloni
Sep 7 '18 at 18:03







I attempted a JS solution (see UPDATE 3) but appear to be having trouble referencing the inputs by name in the Jquery script.

– claudiadast
Sep 7 '18 at 20:20



UPDATE 3



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

How do I collapse sections of code in Visual Studio Code for Windows?

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ