0
votes

I'm trying to validate form by ajax and wtforms, I have a form with one field like this:

name = StringField('Name :', description = "enter your name", validators=[InputRequired(message='please enter your name')])

And my serverside code is like this:

@app.route('/validation', methods=['get', 'post'])
def validation():
    data = request.get_json(force = True)
    myform = MyForm()
    for field in myform:
        field.data = data[field.name]
    myform.validate()
    return jsonify(myform.errors)

I send field data by json and then i set it to field, i checked it and its data exists in myform.data but after validating InputRequired error still exist in response.

2
It is a little bit unclear. Can you try to explain it a bit please :) - Nabin
I get a dictionary of form's data from request and I want to fill the form fields on serverside and validate it, When i fill the fields by a for loop that I mentioned in my question, validate() method does not seem to notice changes, and It returns InputRequired error in my form errors! - sadiq rahmati
Why do you want to do that? - Nabin
to validate form by ajax. - sadiq rahmati
Validation can be done inside the form class. Not sure if validating in views.py is good approach. - Nabin

2 Answers

0
votes

You can validate the form inside the form class itself.

class YouForm(FlaskForm):
    name = StringField('Name :', description = "enter your name", validators=[InputRequired(message='please enter your name')])

    def validate(self):
        valid = True
        if not self.name.data:
            self.name.errors.append('* Either file or text is required')
            valid = False
        return valid

This way you can simply call validate method from view function in views.py file for validation.

0
votes

It you are sending data through ajax and want server side validation just simple use request.form

@app.route('/validation', methods=['get', 'post'])
def validation():
    data = request.get_json(force = True)
    myform = MyForm(request.form)
    if myform.validate():
        #do something
        #return somthing
    else:
        return jsonify(myform.errors)