New to Telerik UI for ASP.NET MVC? 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 = CaptchaHelper.GetNewCaptcha();
    
        Session["captcha" + captchaImage.UniqueId] = captchaImage;
    
        ViewData["Captcha"] = Url.Action("image", "captcha", new { captchaId = captchaImage.UniqueId });
        ViewData["CaptchaID"] = captchaImage.UniqueId;
    }
    

    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();
        }
        else
        {
            CaptchaImage captchaImage = (CaptchaImage)Session["captcha" + captchaModel.CaptchaID];
    
            if (captchaImage != null && CaptchaHelper.Validate(captchaImage, captchaModel.Captcha.ToUpperInvariant()))
            {
                ModelState.Clear();
                GenerateNewCaptcha();
            }
        }
    
        return View();
    }
    
    public ActionResult Image(string captchaId)
    {
        CaptchaImage captcha = (CaptchaImage)Session["captcha" + captchaId];
        var image = CaptchaHelper.RenderCaptcha(captcha);
        byte[] bmpBytes;
    
        using (MemoryStream ms = new MemoryStream())
        {
            image.Save(ms, ImageFormat.Png);
            bmpBytes = ms.ToArray();
        }
    
        return File(bmpBytes, "image/png");
    }
    
    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 = CaptchaHelper.GetNewCaptcha();
    
        Session["captcha" + newCaptcha.UniqueId] = newCaptcha;
    
        return Json(new CaptchaModel
        {
            Captcha = Url.Action("image", "captcha", new { captchaId = newCaptcha.UniqueId }),
            CaptchaID = newCaptcha.UniqueId
        }, JsonRequestBehavior.AllowGet);
    }
    
    public ActionResult Audio(string captchaId)
    {
        CaptchaImage captcha = (CaptchaImage)Session["captcha" + captchaId];
    
        byte[] bmpBytes;
    
        using (MemoryStream audio = CaptchaHelper.SpeakText(captcha))
        {
            bmpBytes = audio.ToArray();
        }
    
        return File(bmpBytes, "audio/wav");
    }
    
    public ActionResult Validate(CaptchaModel model)
    {
        CaptchaImage captchaImage = (CaptchaImage)Session["captcha" + model.CaptchaID];
    
        return Json(CaptchaHelper.Validate(captchaImage, model.Captcha.ToUpperInvariant()), JsonRequestBehavior.AllowGet);
    }
    

    If you don't 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.

    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 MVC 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.

    @model UserViewModel
    
    <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("ready", function() {
            $("#form").kendoValidator();
        });
        function audioHandler(args) {
            args.success("@Url.Action("Audio")?captchaId=" + args.data.CaptchaID);
        }
    </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