As you know Recaptcha is not available on Sitecore 9.0.1 and Sitecore 9.0.2 forms, so I thought to create custom Google Recaptcha but my issue was Google Recaptcha was not working properly on Internet Explorer as it was asking 10 to 15 times to verify which is very frustrating, at the same time it was working for another browser so I thought to create custom Alphanumeric captcha as per client requirement.
In previous blog, we have checked how to create Google reCaptcha field. Now we are going to create Alphanumeric Captcha using below steps:
- Create new viewmodel class AlphaNumericViewModel.cs
[Serializable()] public class AlphaNumericViewModel : StringInputViewModel { protected override void InitItemProperties(Item item) { base.InitItemProperties(item); } }
- Create Controller AlphanumericCaptchaController.cs
public class AlphanumericCaptchaController: SitecoreController
{ public FileResult GetCaptchaImage() { string text = GetRandomText(); System.Web.HttpContext.Current.Session["CAPTCHA"] = text; //first, create a dummy bitmap just to get a graphics object Image img = new Bitmap(1, 1); Graphics drawing = Graphics.FromImage(img); Font font = new Font("Arial", 15); //measure the string to see how big the image needs to be SizeF textSize = drawing.MeasureString(text, font); //free up the dummy image and old graphics object img.Dispose(); drawing.Dispose(); //create a new image of the right size img = new Bitmap((int)textSize.Width + 40, (int)textSize.Height + 20); drawing = Graphics.FromImage(img); Color backColor = Color.Black; Color textColor = Color.White; //paint the background drawing.Clear(backColor); //create a brush for the text Brush textBrush = new SolidBrush(textColor); drawing.DrawString(text, font, textBrush, 20, 10); drawing.Save(); font.Dispose(); textBrush.Dispose(); drawing.Dispose(); MemoryStream ms = new MemoryStream(); img.Save(ms, System.Drawing.Imaging.ImageFormat.Png); img.Dispose(); return File(ms.ToArray(), "image/png"); } private string GetRandomText() { StringBuilder randomText = new StringBuilder(); string alphabets = "012345679ACEFGHKLMNPRSWXZabcdefghijkhlmnopqrstuvwxyz"; Random r = new Random(); for (int j = 0; j <= 5; j++) { randomText.Append(alphabets[r.Next(alphabets.Length)]); } return randomText.ToString(); } }
- Create new AlphaNumericCaptcha.cshtml file on this location “Website/Views/FormBuilder/FieldTemplates”
@using Sitecore.ExperienceForms.Mvc.Html @model <Namespace>.AlphaNumericViewModel <div class="captcha-bar"> <div class="captcha-td"> <img src="@Url.Action("GetCaptchaImage", "AlphanumericCaptcha", new {id = new Random().Next()})" alt="captcha" id="recaptchaImage" class="captcha-text"> <img src="../assets/ACUPublic/img/refresh.png" alt="" id="imgRefresh" class="refresh"> </div> <div class="captcha-td"> <input type="text" id="@Html.IdFor(m => Model.Value)" name="@Html.NameFor(m => Model.Value)" class="@Model.CssClass captcha-input" value="@Model.Value"></div> @Html.ValidationMessageFor(m => Model.Value) </div> <script type="text/javascript"> $("#imgRefresh").click(function (e) { $('#recaptchaImage').attr('src', '@Url.Action("GetCaptchaImage", "Recaptcha")' + '?' + new Date().getTime()); }); </script>
- Create new AlphaNumericCaptcha template on this location “/sitecore/templates/System/Forms/Fields”
- Inherit below templates:
- Switch to Core DB and create copy of this item /sitecore/client/Applications/FormsBuilder/Components/Layouts/PropertyGridForm/PageSettings/Settings/SingleLineText with name “AlphaNumericCaptcha”
- Now move again to Master DB.
- Create new Field type here “/sitecore/system/Settings/Forms/Field Types/Security” with name “Alphanumeric Captcha”
- Fill below details:
- View Path: FieldTemplates/AlphaNumericCaptcha
- Model Type: <Namespace>.AlphaNumericViewModel, <AssemblyName>
- Property Editor: Property Editor Settings/AlphaNumericCaptcha
- Field Template: Fields/AlphaNumericCaptcha
Custom Alphanumeric Validation
- Create new validation class AlpaNumericCaptchaValidator
public class AlpaNumericCaptchaValidator : ValidationElement<string> { public AlpaNumericCaptchaValidator(ValidationDataModel validationItem) : base(validationItem) { } public override void Initialize(object validationModel) { base.Initialize(validationModel); } public override ValidationResult Validate(object value) { if (value == null) { return new ValidationResult(FormatMessage("Invalid Captcha")); } if (HttpContext.Current.Session["CAPTCHA"] == null) { return new ValidationResult(FormatMessage("Session Expired")); } else { if (!value.Equals(HttpContext.Current.Session["CAPTCHA"].ToString())) { return new ValidationResult(FormatMessage("Invalid Captcha")); } else { return ValidationResult.Success; } } } public override IEnumerable<ModelClientValidationRule> ClientValidationRules { get { var rule = new ModelClientValidationRule { ErrorMessage = FormatMessage("Invalid"), }; yield return rule; } } }
- Go to this location “/sitecore/system/Settings/Forms/Validations” and create new validator “AlpaNumericCaptcha Validator”
- In Type field textbox add AlpaNumericCaptchaValidator.cs path like this: <Namespace>.AlpaNumericCaptchaValidator,<AssemblyName>
- Go to this location “/sitecore/system/Settings/Forms/Field Types/Security/Alphanumeric Captcha” and in “Allowed Validations” field select validation which you have created just now.
- Now go to Sitecore Form Editor and you will see Alphanumeric Captcha control inside Security tab
- Drag and drop control into your form
- Do not forget to check “AlphaNumericCaptcha Validator” checkbox otherwise it will not work.
- Render form into your page and Enjoy Alphanumeric Captcha
This article originally appeared on SWATI GUPTA (SITECORE MVP) | BLOGS (https://swatiguptablogs.blogspot.com/).