Google Recaptcha and EPiServer.Forms

icon of user profile

Forms 3.0.0, CMS 9.12, MVC

Last night I played with EPiServer Forms. And there is a sample pack to install as Eric Herlitz blogs about, for the moment containing a calender picker and Googles Recaptcha, real neet!

Install the EPiServer.Forms.Samples: http://www.herlitz.nu/2016/08/30/add-the-missing-date-time-field-in-episerver-forms/

The RecaptchaElementBlock as it is, needs to have specified a sitekey and secret key (Register at https://www.google.com/recaptcha/ to get your keys)

I found it unfortunate that the editors needed to fill in and remember the keys every time, so i found out a way to set them automaticly when the element block is created thanks to Alf Nilssons sample code on github. (by the way setting Allow Anonymous on Forms is a prefered default)

https://github.com/alfnilsson/EpiserverForms/blob/master/Toders.Forms.Web/Business/Forms/AllowAnonymousSubmissionDefault.cs

My code:

using EPiServer.Forms.Samples.Implementation.Elements;

//In initialization
ServiceLocator.Current.GetInstance<IContentEvents>().CreatingContent += SetRecaptchaKeys;

private void SetRecaptchaKeys(object sender, ContentEventArgs e)
{
    if (e.Content is RecaptchaElementBlock)
    {
        ((RecaptchaElementBlock)e.Content).SiteKey = ConfigurationManager.AppSettings["Google.ReCaptcha.Public"] + "";
        ((RecaptchaElementBlock)e.Content).SecretKey = ConfigurationManager.AppSettings["Google.ReCaptcha.Secret"] + "";
    }
}