pythonflaskwtforms

How to validate the array filed in Flask WTForms?


I use Flask as a back-end for handling request from React front-end. I get below request:

{
    "ids":[1,2,3,4,5],
    "other_field":"...",
    "csrf_token":"token"
}

I use wtforms to validate my inputs. For ids param, the front-end should send array with at least one value and not exceed 10 values, otherwise it should not validate the form.

I tried below code, without getting desire result.

class validate(FlaskForm):
    # other validations
    ids      = FieldList(IntegerField('ids'), min_entries=1, max_entries=10)

Solution

  • Based on @Detlef advice I switched to webargs. Below code Gives me the desire result.

    from webargs import fields, validate
    from webargs.flaskparser import use_args
    
    @app.route("/",methods=['POST'])
    @use_args({
        "ids": fields.List(fields.Int(),required=True, validate=[validate.Length(min=1, max=10)])
    }, location="json")
    def index(args):
        return args["ids"]