Validator TagHelper Overview

The Telerik UI Validator TagHelper for ASP.NET Core is a server-side wrapper for the Kendo UI Validator widget.

The Validator offers options for implementing client-side form validation.

Telerik UI for ASP.NET Core Ninja image

The Validator is part of Telerik UI for ASP.NET Core, a professional grade UI library with 110+ components for building modern and feature-rich applications. To try it out sign up for a free 30-day trial.

Initializing the Validator

The following example demonstrates how to define the Validator by using the Validator TagHelper.

    @{
        var messages = new Dictionary<string, string>() { { "custom", "Please choose another Start Time." } };
        var rules = new Dictionary<string, string>() { { "custom", "customFunction" } };
    }
    <form id="ticketsForm" kendo-validator="true" kendo-messages="messages" kendo-rules="rules">
        <ul id="fieldlist">
            <li>
                <label for="fullname" class="required">Your Name</label>
                @(Html.Kendo().TextBox()
                    .Name("fullname")
                    .HtmlAttributes(new { placeholder = "Full name", required = "required", style = "width:220px" })
                )
            </li>
        </ul>
    </form>
    <script>
        function customFunction(input) {

            if (input.attr('name') === "time" && input.val() == "14:00") {
                return false;
            }

            return true;
        }

        $(document).ready( function () {
            var validator = $("#ticketsForm").data("kendoValidator");
            var validationSummary = $("#validation-summary");

            $("form").submit(function(event) {
                event.preventDefault();

                if (validator.validate()) {
                    validationSummary.html("<div class='k-messagebox k-messagebox-success'>Hooray! Your tickets has been booked!</div>");
                } else {
                    validationSummary.html("<div class='k-messagebox k-messagebox-error'>Oops! There is invalid data in the form.</div>");
                }
            });
        });
    </script>

Using the DataAnnotation Attributes

The Validator creates validation rules based on the unobtrusive HTML attributes. They are generated by Telerik UI for ASP.NET Core based on the DataAnnotation attributes that are applied to the Model properties. The Validator also creates rules for the unobtrusive attributes that are generated implicitly by MVC for numbers and dates.

DataAnnotation supports the following attributes:

  • Required
  • StringLength
  • Range
  • RegularExpression

To use the Validator with the DataAnnotation attributes:

  1. Create a class and add the needed DataAnnotation attributes.

        public class OrderViewModel
        {
            [HiddenInput(DisplayValue = false)]
            public int OrderID { get; set; }
    
            [Required]
            [Display(Name = "Customer")]
            public string CustomerID { get; set; }
    
            [Required]
            [StringLength(15)]
            [Display(Name = "Ship Country")]
            public string ShipCountry { get; set; }
    
            [Required]
            [Range(1, int.MaxValue, ErrorMessage = "Freight should be greater than 1")]
            [DataType(DataType.Currency)]
            public decimal? Freight { get; set; }
    
            [Required]
            [Display(Name = "Order Date")]
            public DateTime? OrderDate { get; set; }
        }
    
  2. Pass an instance of the Model to the View.

       public ActionResult Create()
        {                
            return View(new OrderViewModel());
        }
    
  3. Create a form with editors based on the Model and initialize the Validator on the form.

        @model OrderViewModel
    
        <form id="exampleForm" kendo-validator="true">
            <fieldset>
                <legend>Order</legend>
    
                @Html.HiddenFor(model => model.OrderID)
    
                <div class="editor-label">
                    @Html.LabelFor(model => model.CustomerID)
                </div>
                <div class="editor-field">
                    @(Html.Kendo().DropDownListFor(model => model.CustomerID)
                        .OptionLabel("Select Customer")
                    )
                    @Html.ValidationMessageFor(model => model.CustomerID)
                </div>
    
                <div class="editor-label">
                    @Html.LabelFor(model => model.ShipCity)
                </div>
                <div class="editor-field">
                    @Html.EditorFor(model => model.ShipCity)
                    @Html.ValidationMessageFor(model => model.ShipCity)
                </div>
    
                <div class="editor-label">
                    @Html.LabelFor(model => model.Freight)
                </div>
                <div class="editor-field">
                    @Html.Kendo().NumericTextBoxFor(model => model.Freight)
                    @Html.ValidationMessageFor(model => model.Freight)
                </div>
    
                <div class="editor-label">
                    @Html.LabelFor(model => model.OrderDate)
                </div>
                <div class="editor-field">
                    @Html.Kendo().DatePickerFor(model => model.OrderDate)
                    @Html.ValidationMessageFor(model => model.OrderDate)
                </div>
                <p>
                    <input type="submit" value="Save" />
                </p>
            </fieldset>
        </form>
    

Employing jQuery Validation

  1. Add the latest version of the jquery.validate and jquery.validate.unobtrusive scripts to the project.
  2. Include them in the View, in which you want to validate the user input, or in the _Layout.cshtml.
  3. After including the scripts, override the default ignore setting to enable the validation of the hidden elements—for example, helpers like the DropDownList and NumericTextBox have a hidden input to keep the value.

        <script src="~/jquery.validate.min.js")"></script>
        <script src="~/jquery.validate.unobtrusive.min.js")"></script>
        <script type="text/javascript">
            $.validator.setDefaults({
                ignore: ""
            });
        </script>
    
  4. Define the Model and create the editors. For more information, refer to the section on using the Validator with DataAnnotation attributes.

See Also

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