New to Telerik UI for ASP.NET Core? Download free 30-day trial

Captcha Validation Setup

This article explains how to use your application's backend to verify the user's response to the Telerik UI Captcha.

Always generate the CAPTCHA and apply the validation on the server-side of your application. This approach guarantees that no programs or bots can access the values of the CAPTCHA on the client-side via JavaScript and then bypass the validation.

To proceed with the tutorial below, make sure that the Captcha Server-side Provider is added and referenced in your project.

Getting Started

To generate CAPTCHAs and validate the user's input, the Telerik UI Captcha depends on the following main options:

  • Handler—Sets the URL handler, function, or action configuration that fetches the generated image.
  • AudioHandler—Sets the URL handler, function, or action configuration that fetches the generated audio.
  • ValidationHandler—Sets the URL handler, function, or action configuration that can validate the captcha remotely.

  1. To generate a new CAPTCHA, use the GetNewCaptcha() method of the CaptchaHelper. Save the CAPTCHA to a Session.

    private void GenerateNewCaptcha()
    {
        CaptchaImage captchaImage = SetCaptchaImage();
    
        ViewData["Captcha"] = "./shared/UserFiles/captcha/" + captchaImage.UniqueId + ".png";
        ViewData["CaptchaID"] = captchaImage.UniqueId;
    }
    
    private CaptchaImage SetCaptchaImage()
    {
        CaptchaImage newCaptcha = CaptchaHelper.GetNewCaptcha();
    
        MemoryStream audio = CaptchaHelper.SpeakText(newCaptcha);
        using (FileStream file = new FileStream(Path.Combine(CaptchaPath, newCaptcha.UniqueId + ".wav"), FileMode.Create, FileAccess.Write))
        {
            audio.WriteTo(file);
        }
    
        var image = CaptchaHelper.RenderCaptcha(newCaptcha);
        image.Save(Path.Combine(CaptchaPath, newCaptcha.UniqueId + ".png"), ImageFormat.Png);
    
        HttpContext.Session.SetString("captcha_" + newCaptcha.UniqueId, newCaptcha.Text);
    
        return newCaptcha;
    }
    

    Generate the CAPTCHA in the ActionMethod that returns the Razor View. If the CAPTCHA is used in multiple Razor Views, generate it in the Controller's constructor.

    public ActionResult Index(UserViewModel user, CaptchaModel captchaModel)
    {
        if (string.IsNullOrEmpty(captchaModel.CaptchaID))
        {
            GenerateNewCaptcha();
            return View();
        }
        else
        {
            string text = GetCaptchaText(captchaModel.CaptchaID);
    
            if (text == captchaModel.Captcha.ToUpperInvariant())
            {
                ModelState.Clear();
                GenerateNewCaptcha();
            }
        }
    
        return View(user);
    }
    
    
    public class CaptchaModel
    {
        private string _captchaValue;
        public string Captcha {
            get
            {
                return string.IsNullOrEmpty(_captchaValue) ? "" : _captchaValue;
            }
            set
            {
                _captchaValue = value;
            }
        }
        public string CaptchaID { get; set; }
    }
    
  2. Introduce the Telerik UI Captcha in a Razor View:

    @(Html.Kendo().Captcha()
        .Name("Captcha")
        .CaptchaImage((string)ViewData["Captcha"])
        .CaptchaId((string)ViewData["CaptchaID"])
        .DataCaptchaField("Captcha") // The field containing the Captcha from the server-side should be called Captcha.
        .DataCaptchaIdField("CaptchaID") // The field containing the Captcha's ID from the server-side should be called CaptchaID.
        .Handler(handler => handler.Action("Reset", "Captcha"))
        .AudioHandlerFunction("audioHandler")
        .ValidationHandler(handler => handler.Action("Validate", "Captcha"))
        .ValidateOnBlur(true)
    )
    
    <script>
        function audioHandler(args) {
            args.success("@Url.Action("Audio")?captchaId=" + args.data.captchaId);
        }
    </script>
    
  3. Add the server-side handlers for the Captcha:

    public ActionResult Reset()
    {
        CaptchaImage newCaptcha = SetCaptchaImage();
    
        return Json(new CaptchaModel
        {
            Captcha = "./shared/UserFiles/captcha/" + newCaptcha.UniqueId + ".png",
            CaptchaID = newCaptcha.UniqueId
        });
    }
    
    public ActionResult Validate(CaptchaModel model)
    {
        string text = GetCaptchaText(model.CaptchaID);
    
        return Json(text ==  model.Captcha.ToUpperInvariant());
    }
    

    If you omit to set the CaptchaImage and CaptchaId options, the widget will not have an image preloaded. When initialized, it will fetch the image from the Handler() option.

    Instead of the ViewData, you could use the page's model.

Form Integration

The Telerik UI Captcha for ASP.NET Core prevents automated programs from performing tasks such as form submissions. If the user does not enter the text from the CAPTCHA image correctly, a validation error is shown and the form submission is aborted.

  1. Create a form and add the Telerik UI Captcha.

    <form id="form" method="POST">
        @(Html.Kendo().TextBoxFor(m => m.UserName))
        @(Html.Kendo().TextBoxFor(m => m.FirstName))
        @(Html.Kendo().TextBoxFor(m => m.LastName))
        @(Html.Kendo().Captcha()
            .Name("Captcha")
            .CaptchaImage((string)ViewData["Captcha"])
            .CaptchaId((string)ViewData["CaptchaID"])
            .DataCaptchaField("Captcha")
            .DataCaptchaIdField("CaptchaID")
            .Handler(handler => handler.Action("Reset", "Captcha"))
            .AudioHandlerFunction("audioHandler")
            .ValidationHandler(handler => handler.Action("Validate", "Captcha"))
        )
        @(Html.Kendo().Button()
            .Name("Submit")
            .Content("Submit")
            .HtmlAttributes(new { type="submit" })
        )
    </form>
    
  2. Instantiate a Telerik UI Validator from the form inside the document.ready() event.

    <script>
        $(document).on("kendoReady", function () {
            $("#form").kendoValidator();
        });
        function audioHandler(args) {
            args.success("./shared/UserFiles/captcha/" + args.data.CaptchaID + ".wav");
        }
    </script>
    

If the state of the Telerik UI Captcha is invalid, the Validator prevents the form submission and shows an error message to the user.

See Also

In this article
Not finding the help you need? Improve this article