# 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](https://www.telerik.com/aspnet-core-ui/documentation/html-helpers/editors/captcha/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.

   ```C#
   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);

       var key = newCaptcha.UniqueId;
       var value = JsonConvert.SerializeObject(newCaptcha);
       HttpContext.Session.SetString("captcha_" + key, value);

       return newCaptcha;
   }
   ```

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

   ```C# Controller
   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);
   }
   ```

   ```C# CaptchaModel.cs
   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:

   ```Razor HtmlHelper
   @(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)
   )
   ```

   ```Razor TagHelper
   <kendo-captcha name="Captcha"
                  captcha-image="@ViewData["Captcha"]"
                  captcha-id="@ViewData["CaptchaID"]"
                  datacaptchafield="Captcha"
                  datacaptchaidfield="CaptchaID"
                  validate-on-blur="true">
       <handler url="@Url.Action("Reset", "Captcha")" />
       <audio-handler function-handler="audioHandler" />
       <validation-handler url="@Url.Action("Validate", "Captcha")" />
   </kendo-captcha>
   ```

   ```JavaScript
   <script>
       function audioHandler(args) {
           args.success("@Url.Action("Audio")?captchaId=" + args.data.captchaId);
       }
   </script>
   ```

3. Add the server-side handlers for the Captcha:

   ```C#
   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.

   > tip Instead of the **ViewData**, you could use the [page's model](https://docs.microsoft.com/en-us/aspnet/core/mvc/views/overview?view=aspnetcore-5.0#passing-data-to-views).

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

   ```Razor HtmlHelper
   @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>
   ```

   ```Razor TagHelper
   @model UserViewModel

   <form id="form" method="POST">
       <kendo-textbox for="@Model.UserName"></kendo-textbox>
       <kendo-textbox for="@Model.FirstName"></kendo-textbox>
       <kendo-textbox for="@Model.LastName"></kendo-textbox>

       <kendo-captcha name="Captcha"
                      captcha-image="@ViewData["Captcha"]"
                      captcha-id="@ViewData["CaptchaID"]"
                      datacaptchafield="Captcha"
                      datacaptchaidfield="CaptchaID">
           <handler url="@Url.Action("Reset", "Captcha")" />
           <audio-handler function-handler="audioHandler" />
           <validation-handler url="@Url.Action("Validate", "Captcha")" />
       </kendo-captcha>

       <kendo-button name="Submit" type="submit">
           Submit
       </kendo-button>
   </form>
   ```

2. Instantiate a Telerik UI Validator from the form inside the [document.ready() event](https://learn.jquery.com/using-jquery-core/document-ready/).

   ```JavaScript
   <script>
       $(document).on("ready", 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

* [Form Integration of the Captcha HtmlHelper for ASP.NET Core (Demo)](https://demos.telerik.com/aspnet-core/captcha/index)
* [Server-Side API](https://www.telerik.com/aspnet-core-ui/documentation/api/captcha)
