title: Converting Flask validation errors to JSON
body: <p>I'm using Flask as my backend to create user accounts through an iOS application.  I can successfully create accounts, but I'm not too sure how I'm suppose to return the validation errors I get when username/email are already in use.  I'm thinking that when the form gets validated, it should return a dictionary of possible errors that gets converted to JSON and sent back to the app but not too sure how to approach this.  </p>
  
  <pre><code>//form.py
  class RegistrationForm(Form):
      email = StringField('Email', validators=[Required()])
      username = StringField('Username', validators=[Required()])
      password_hash = StringField('Password', validators=[Required()])
  
      def validate_email(self, field):
          if User.query.filter_by(email=field.data).first():
              print("Email already registered.")
              raise ValidationError('Email already registered.')
  
      def validate_username(self, field):
          if User.query.filter_by(username=field.data).first():
              print("Username already in use.")
              errorDict={'username': 'Username already in use.'}
              raise ValidationError('Username already in use.')
  </code></pre>
  
  <p>EDIT:
  I modified the register function to test for various cases.  This is definitely not a good way of doing it, but its holding me over for now.</p>
  
  <pre><code>//userRegistration.py
  @auth.route('/register', methods=['POST'])
  def register():
      try:
          data = MultiDict(mapping=request.json)
          form = RegistrationForm(data)
  
          if form.validate():
              user = User.register_fromJSON(request.json)
              db.session.add(user)
              db.session.commit()
              return jsonify({'success': 1})
          else:
              if form.email.errors and form.username.errors:
                  print('case1')
                   return jsonify({'emailError': form.email.errors[0], 'usernameError': form.username.errors[0]})
              elif form.email.errors and not form.username.errors:
                  print('case2')
                  return jsonify({'emailError': form.email.errors[0]})
              elif form.username.errors and not form.email.errors:
                  print('case3')
                  return jsonify({'usernameError': form.username.errors[0]})
  
      except Exception:
          return jsonify({'Success': 0})
  </code></pre>