New to Telerik UI for ASP.NET CoreStart a free 30-day trial

Validation

Telerik UI for ASP.NET Core enables you to use client-side validation by utilizing the Kendo UI for jQuery Validator or the default jQuery validation.

This article covers the implementation of validation using DataAnnotation attributes to create validation rules based on unobtrusive HTML attributes and describes how to activate the Kendo UI Validator on the client. It also explains how to create custom validation rules, extend the built-in validation rules of the editable UI components, such as Grid and ListView, or use the jQuery validation when using Telerik UI for ASP.NET Core components.

Using DataAnnotation Attributes

The Telerik UI HTML and Tag Helpers consume the DataAnnotation attributes that are added to the Model. This way, the server-side validation is performed using the ModelState, which is updated based on these validation rules (for example, ModelState.IsValid).

The Telerik UI for ASP.NET Core editors support the following DataAnnotation attributes:

  • DataTypeAttribute
  • EmailAddress
  • MaxLengthAttribute
  • MinLengthAttribute
  • Range
  • RegularExpression
  • Required
  • StringLength
  • UrlAttribute

The HTML5 data-* attributes are generated in the HTML markup of each editor component based on the DataAnnotation attributes applied to the Model properties. To enable the client-side validation, the Kendo UI for jQuery Validator must be activated on the form that contains the editor components. The Validator automatically creates validation rules based on the unobtrusive HTML attributes. Also, the Validator creates rules for the unobtrusive attributes that are generated implicitly by ASP.NET Core for numbers and dates.

The following example demonstrates how to enable the Kendo UI Validator to perform client-side validation based on the applied DataAnnotation attributes.

  1. Create a Model and set the desired DataAnnotation attributes.

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

    C#
        public IActionResult Create()
        {                
            return View(new OrderViewModel());
        }
  3. Create the editors in the View based on the Model properties and initialize the Validator on the form by setting kendo-validator="true" in the form's tag.

    Razor
        @addTagHelper *, Kendo.Mvc
        @model OrderViewModel
    
        <form id="exampleForm" asp-controller="Home" asp-action="Create" method="post" class="k-form k-form-vertical" 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().TextBoxFor(model => model.CustomerID))
                    @Html.ValidationMessageFor(model => model.CustomerID)
                </div>
                <div class="editor-label">
                    @Html.LabelFor(model => model.ShipCountry)
                </div>
                <div class="editor-field">
                    @(Html.DropDownListFor(model => model.ShipCountry)
                        .BindTo(new List<string>() {
                            "Country A",
                            "Country B",
                            "Country C"
                        })
                    )
                    @Html.ValidationMessageFor(model => model.ShipCountry)
                </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>
                    @(Html.Kendo().Button()
                        .Name("submitBtn")
                        .HtmlAttributes(new { type = "submit" })
                        .Content("Submit")
                    )
                </p>
            </fieldset>
        </form>

    Alternatively, you can initialize the Validator with jQuery when the page with the form is loaded:

    Razor
        @model OrderViewModel
    
        <form id="exampleForm" asp-controller="Home" asp-action="Create" method="post" class="k-form k-form-vertical">
            ...
        </form>
    
        <script>
         $(document).ready(function() {
             $("#exampleForm").kendoValidator(); // Select the form by "id" or "class" with jQuery.
         });
        </script>

For a live example, visit the Basic Usage demo of the Validator.

Implementing Custom Attributes

To use custom DataAnnotation attributes, define the custom rules when initializing the Validator.

For example, you can implement a GreaterDateAttribute attribute to check whether the selected ShippedDate value is greater than the selected OrderDate.

  1. Create a class that inherits from the ValidationAttribute class and implements the IClientModelValidator interface. Add the IsValid and AddValidation methods.

    C#
        [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
        public class GreaterDateAttribute : ValidationAttribute, IClientModelValidator
        {
            public string EarlierDateField { get; set; }
    
            protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            {
                DateTime? date = value != null ? (DateTime?)value : null;
                var earlierDateValue = validationContext.ObjectType.GetProperty(EarlierDateField)
                    .GetValue(validationContext.ObjectInstance, null);
                DateTime? earlierDate = earlierDateValue != null ? (DateTime?)earlierDateValue : null;
    
                if (date.HasValue && earlierDate.HasValue && date <= earlierDate)
                {
                    return new ValidationResult(ErrorMessage);
                }
    
                return ValidationResult.Success;
            }
    
            public void AddValidation(ClientModelValidationContext context)
            {
                MergeAttribute(context.Attributes, "data-val", "true");
                var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
                MergeAttribute(context.Attributes, "data-val-greaterdate", errorMessage);
    
                context.Attributes["earlierdate"] = EarlierDateField;
            }
    
            // Helper method
            private bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
            {
                if (attributes.ContainsKey(key))
                {
                    return false;
                }
                attributes.Add(key, value);
                return true;
            }
        }
  2. Decorate the ShippedDate property with the newly implemented attribute.

    C#
        public class OrderViewModel
        {
            // Omitted for brevity.
    
            [Display(Name = "Order Date")]
            [DataType(DataType.Date)]
            public DateTime? OrderDate { get; set; }
    
            [GreaterDate(EarlierDateField = "OrderDate", ErrorMessage = "Shipped date should be after Order date")]
            [DataType(DataType.Date)]
            public DateTime? ShippedDate { get; set; }
        }
  3. Implement the custom Validator rule to handle all inputs with the data-val-greaterdate attribute.

    Razor
        @model OrderViewModel
    
        <form id="exampleForm" asp-controller="Home" asp-action="Create" method="post" class="k-form k-form-vertical">
            <fieldset>
                <legend>Order</legend>
                @Html.HiddenFor(model => model.OrderID)
                <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>
                <div class="editor-label">
                    @Html.LabelFor(model => model.ShippedDate)
                </div>
                <div class="editor-field">
                    @Html.Kendo().DatePickerFor(model => model.ShippedDate)
                    @Html.ValidationMessageFor(model => model.ShippedDate)
                </div>
                <p>
                    @(Html.Kendo().Button()
                        .Name("submitBtn")
                        .HtmlAttributes(new { type = "submit" })
                        .Content("Submit")
                    )
                </p>
            </fieldset>
        </form>
  4. To trigger the custom serve-side validation employed from the attribute, use the ModelState.IsValid property.

    C#
        [HttpPost]
        public IActionResult Submit(OrderViewModel formData)
        {
            if (!ModelState.IsValid)
            {
                // Handle server-side error.
            }
    
            return View(model);
        }

Applying Custom Attributes in Editable Helpers

The editable helpers, such as the Grid and ListView, initialize the Validator internally. To specify custom rules, you have to extend the built-in validation rules of the Validator. You can also use this approach to define rules and reuse them in all Views.

The following example shows how to implement a CustomProductNameValidation attribute to check whether the entered ProductName starts with a capital letter.

C#
    using System.ComponentModel.DataAnnotations;
    using System.Text.RegularExpressions;

	public class ProductViewModel
	{
		public int ProductID { get; set; }

		[Required]
		[CustomProductNameValidation(ErrorMessage = "ProductName should start with capital letter")]
		public string ProductName { get; set; }
	}

	public class CustomProductNameValidationAttribute : ValidationAttribute
	{		
		public override bool IsValid(object value)
		{
			var productName = (string)value;
			if (!string.IsNullOrEmpty(productName))
			{
				return Regex.IsMatch(productName, "^[A-Z]");
			}
			return true;
		}
	}

For a live example, visit the Custom Validator demo of the Grid.

Employing jQuery Validation

To use jQuery for the client-side validation of the Model, follow the steps below:

  1. Add the latest version of the jquery.validate and jquery.validate.unobtrusive packages to the project.

  2. Include the scripts in the View with the editors, which must be validated based on the user input or in the _Layout.cshtml file.

  3. After registering 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, which holds the value.

    HTML
        <script src="~/lib/jquery-validation/jquery.validate.min.js"></script>
        <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
        <script type="text/javascript">
            $.validator.setDefaults({
                ignore: ""
            });
        </script>
  4. Define the Model and the editors on the View.

See Also