2

I'm using bootstrap/wtf.html template to display my forms. All my form input fields have wtform validators allowing me to define a custom error message. Unfortunately the RecaptchaField imported from flask_wtf does not seem to support validators (not with the goal of validating it, as it's done automatically, but for defining a custom error message). The user should not be facing technical messages but only a nice generic one. What would be the easiest and cleanest option to define my custom message, still by using bootstrap/wtf template? Other option would be to stop rendering the recaptcha field with the template but I would rather not do that if possible.

Thank you !

user5228239
  • 103
  • 1
  • 1
  • 5

2 Answers2

2

Pass the custom error message when creating field. For example:

from flask_wtf.recaptcha import RecaptchaField, Recaptcha

class SignupForm(Form):
    email = EmailField('Email')
    recaptcha = RecaptchaField(validators=[Recaptcha(message="Your custom message")])
    submit = InlineSubmitField('Join Now')
Gitau Harrison
  • 3,179
  • 1
  • 19
  • 23
Pooja
  • 736
  • 1
  • 13
  • 29
0
from flask_wtf.recaptcha.fields import RecaptchaField
from wtforms import Form, BooleanField, StringField, PasswordField, IntegerField, validators
from flask import render_template, request, redirect, url_for, jsonify


class InquiryForm(Form):
      email = StringField('email', [validators.Email(message=(u'invalid email address'))])
      recaptcha = RecaptchaField()

@app.route('/inquiry', methods=['POST','GET'])
def inquiry():
form = InquiryForm(request.form)
if request.method == 'POST' and form.validate():
   return jsonify({'success' : 'Message sent'})
else:
    # request.form.get('g-recaptcha-response')
    # google recaptcha v2 validate return
    if request.form.get('g-recaptcha-response') and form.recaptcha.errors:
       form.recaptcha.errors.append("System has detected possible suspicious activity, please refresh this page.")
       form.recaptcha.errors.reverse()
    elif form.recaptcha.errors:
       form.recaptcha.errors.append("Need to validate recaptcha")
       form.recaptcha.errors.reverse()

    return jsonify(form.errors)

Here's how I append custom recaptcha error message

Sourcephy
  • 239
  • 4
  • 4