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

Azure AD Integration with Sitecore 10.2

 Azure AD Integration with Sitecore 10.2 Sitecore identity server that comes with Sitecore 9.1 allows you to log in through an external identity provider like Azure Active Directory, Facebook, Apple, or Google. It is built on Federation Authentication. What is Federation Authentication? Federation authentication is a technology to allows users to access multiples application, tools, and domains using one credential. Using one set of credential user can access multiple applications, and resources after authentication.  Federation authentication consists of two systems, the Identity provider and the Service provider. Identity providers that maintain/create/manage identity information like name, email address, device, and location. Some examples of identity providers are Azure AD, Google, Facebook, and Apple. Service providers basically refer to a website, software, or app that the user is trying to access and SP basically relies on the identity provider to authenticate the user and provi

Sitecore 10.2 - “Failed to start service ‘Sitecore Marketing Automation Engine’” on Windows 11

Sitecore 10.2 - “Failed to start service ‘Sitecore Marketing Automation Engine' ” on Windows 11 Today I started to install Sitecore 10.2 using Sitecore Instance Manager on Windows 11 and I got this issue “Failed to start service ‘Sitecore Marketing Automation Engine' ” . Error : On event viewer it was showing the below error: I also tried to run ‘ Sitecore.MAEngine.exe ’ like this C:\Windows\system32>C:\inetpub\wwwroot\sclocal102xconnect.dev.local\App_Data\jobs\continuous\AutomationEngine\Sitecore.MAEngine.exe Which was throwing below error: Starting Marketing Automation Engine... 2022-01-29 22:21:11 ERR Error initializing XConnect client. System.AggregateException: One or more errors occurred. ---> Sitecore.XConnect.XdbCollectionUnavailableException: An error occurred while sending the request. ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: An unexpected err

Sitecore CDP Certification - Tips and Tricks

Sitecore CDP Certification - Tips and Tricks Recently I completed Sitecore CDP (Customer Data Platform) certification. In this blog, I will share my personal experience and the steps I took to successfully complete the Sitecore CDP certification. Before diving into the certification journey, I researched various resources to plan my preparation effectively: CDP Certificate Competency  Competency 1: Customer Data Platform Competency 2: Real-time Behavior Data Ingestion Competency 3: Interactive API Competency 4: Batch Data Ingestion Competency 5: Audience Sync and Batch Segments Official Documentation https://doc.sitecore.com/cdp/en/users/sitecore-cdp/index-en.html   https://doc.sitecore.com/cdp/en/developers/api/index-en.html#UUID-980f86cc-d900-1d49-3523-030e16d197a2  https://doc.sitecore.com/cdp/ https://learning.sitecore.com/pages/66/sitecore-learning-home CDP & Personalize Mind Map A highly beneficial resource you can discover is the Mind Map . Exam Details The Sitecore CDP Cert