Skip to main content

Sitecore 9 Forms :  Alphanumeric Captcha

Sitecore 9 Forms :  Alphanumeric Captcha

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:

Alphanumeric Captcha

  • 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:
a.      View Path: FieldTemplates/AlphaNumericCaptcha
b.      Model Type:  <Namespace>.AlphaNumericViewModel, <AssemblyName>
c.      Property Editor: Property Editor Settings/AlphaNumericCaptcha
d.      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

Alphanumeric Captcha



  •        Drag and drop control into your form
  •      Do not forget to check “AlphaNumericCaptcha Validator” checkbox otherwise it will not work.

Alphanumeric Captcha


  •      Render form into your page and Enjoy Alphanumeric Captcha

   

Comments

Popular posts from this blog

Sitecore Certification Sample Questions

Sitecore Certification Sample Questions I have completed the Sitecore 9 certification in 2019 and Sitecore 8.2 Certification in 2018. Let me tell you if you have some knowledge about Sitecore then it will be easier for you to understand questions and clear certification exam. Your main focus should be to understand the questions and answers carefully because it is too confusing There will be two options to give the exam: Install the software in your laptop (Laptop should have mic and webcam) Authorized training Center If you have proper Internet, then you can choose option 1 otherwise option 2 is a good choice. Disclaimer : Please note that the below question is only for information purpose only. Below question does not claim the accuracy of the content. Sample Questions: Question 1: What is the name of Component architecture guideline of Sitecore? Answer : Helix Question 2 : What is horizontal scaling and vertical scaling? Answer :  https://doc.

Sitecore 9 Forms: Google reCaptcha field

Sitecore 9 Forms: Google reCaptcha field  Re-Captcha is the most important part of any form’s submission. Google reCaptcha run internet bot detector and determined whether a user is a bot or not.  Sitecore Forms does not provide Google reCaptcha field, which was available in WFFM before, so I have created my custom Google reCaptcha.   Below you can find step by step process to create Google reCaptcha field. Create patch config for reCaptcha Sitekey and SecretKey <?xml version="1.0"?> <configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/"> <sitecore> <settings> <setting name="ReCaptchaSiteKey" value="site-key" /> <setting name="ReCaptchaSecretKey" value="secret-key" /> </settings> </sitecore> </configuration> Create new viewmodel class RecaptchaViewMode

Create Sitecore Custom Admin Page

Create Sitecore Custom Admin Page Sitecore provides you lots of Admin pages just like ShowConfig.aspx, cache.aspx, Logs.aspx, howServicesConfig.aspx, etc. which you can check from here http://<yoursite>/sitecore/admin/. All Sitecore Admin pages is available in this folder “sitecore/admin/*” Sometimes there can be requirement that you want to create custom Admin page which will be accessible to Admin/Non-Admin user. Here is an example: Create aspx page “CustomAdminPage.aspx” inside “<root>/sitecore/admin” folder <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CustomAdminPage.aspx.cs" Inherits="Namespace.CustomAdminPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Custom Admin Page</title> <link rel="stylesheet" type="text/css" href="/sitecore/she