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

Validation

Telerik UI for ASP.NET MVC 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 MVC components.

Using DataAnnotation Attributes

The Telerik UI HTML 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 MVC 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 MVC 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 ActionResult Create()
        {                
            return View(new OrderViewModel());
        }
  3. Create the editors in the View based on the Model properties and initialize the Validator on the form with jQuery when the page with the form is loaded:

    Razor
    @model OrderViewModel
    
    @using (Html.BeginForm()) {
        <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>
                <input type="submit" value="Save" />
            </p>
        </fieldset>
    }
    
    <script>
        $(function () {
            $("form").kendoValidator(); // Select the form 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 IClientValidatable interface. Add the IsValid and GetClientValidationRules methods.

    C#
        [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
        public class GreaterDateAttribute : ValidationAttribute, IClientValidatable
        {
            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 IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
            {
                var rule = new ModelClientValidationRule
                {
                    ErrorMessage = ErrorMessage,
                    ValidationType = "greaterdate"
                };
    
                rule.ValidationParameters["earlierdate"] = EarlierDateField;
    
                yield return rule;
            }
        }
  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
    
        @using (Html.BeginForm()) {
            <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>
                    <input type="submit" value="Save" />
                </p>
            </fieldset>
        }
    
        <script>
            $(function () {
                $("form").kendoValidator({
                    rules: {
                        greaterdate: function (input) {
                            if (input.is("[data-val-greaterdate]") && input.val() != "") {
                                var date = kendo.parseDate(input.val()),
                                    earlierDate = kendo.parseDate($("[name='" + input.attr("data-val-greaterdate-earlierdate") + "']").val());
                                return !date || !earlierDate || earlierDate.getTime() < date.getTime();
                            }
    
                            return true;
                        }
                    },
                    messages: {
                        greaterdate: function (input) {
                            return input.attr("data-val-greaterdate");
                        }
                    }
                });
            });
        </script>
  4. To trigger the custom serve-side validation employed from the attribute, use the ModelState.IsValid property.

    C#
        [HttpPost]
        public ActionResult 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 CustomValidationProductViewModel
    {
        public int ProductID { get; set; }

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

    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class CustomProductNameValidationAttribute : ValidationAttribute, IClientValidatable
    {
        public override bool IsValid(object value)
        {
            var productName = (string) value;
            if (!string.IsNullOrEmpty(productName))
	        {                
		        return Regex.IsMatch(productName, "^[A-Z]");
            }
            return true;            
        }        

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationRule
            {
                ErrorMessage = ErrorMessage,
                ValidationType = "productnamevalidation"
            };
        }        
    }

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="@Url.Content("~/Scripts/jquery-validation/jquery.validate.min.js")"></script>
        <script src="@Url.Content("~/Scripts/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