Reputation: 53
req = request.get_json()
for key in req:
if req[key] == '':
err = {
f"{key}": [f"{key} is required!"]
}
error = make_response(jsonify(error = err), 400)
print(error)
return error
Hello all, What I am trying to do is to validate user form input data coming from javacsript axios, if a field is empty it should return error response as JSON. something like:
"error": {
"username" : "username required!",
"e-mail" : "email is required!"
}
these errors should depend on empty fields on a form. I want to return the error in JSON from flask to javascript and use the error response to display on my HTML form. but the code doesn't iterate through all the JSON post request data. it only returns one field error when there are 5 empty fields. how do i iterate through the json post request and check for empty fields to return error json response to javascript?
Upvotes: 1
Views: 371
Reputation: 260
You return as soon as you find one error that's why you get result with only one error
req = request.get_json()
errors = {}
for key in req:
if req[key] == '':
errors[key] = f"{key} is required!"
if len(errors) > 0:
return make_response(jsonify(error = errors), 400)
Upvotes: 1