Edit this page

Validation

This article describes how to use client-side validation with Progress Telerik UI for ASP.NET MVC. It also provides hints on how to use the Kendo UI Validator and the MVC default jQuery validation.

Common Scenarios

Use DataAnnotation Attributes

The Kendo UI Validator creates validation rules based on the unobtrusive HTML attributes. Those unobtrusive attributes are generated by ASP.NET MVC, based on the DataAnnotation attributes applied to the Model properties.

Currently, the supported DataAnnotation attributes are:

  • Required
  • StringLength
  • Range
  • RegularExpression

The Kendo UI Validator also creates rules for the unobtrusive attributes that are generated for numbers and dates implicitly by MVC.

Below are listed the steps for you to follow when using the Kendo UI Validator with the DataAnnotation attributes.

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

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

    Example
        public ActionResult Create()
        {
            ViewData["customers"] = GetCustomers();
            return View(new OrderViewModel());
        }
    
  3. Create the editors in the view based on the model, and initialize the Kendo UI Validator on the form.

    Example
        @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().DropDownListFor(model => model.CustomerID)
                            .OptionLabel("Select Customer")
                            .BindTo(ViewData["customers"] as SelectList)
                    )
                    @Html.ValidationMessageFor(model => model.CustomerID)
                </div>
    
                <div class="editor-label">
                    @Html.LabelFor(model => model.ShipCountry)
                </div>
                <div class="editor-field">
                    @Html.EditorFor(model => model.ShipCountry)
                    @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();
            });
        </script>
    

Implement Custom Attributes

If you come across a scenario where the built-in rules cannot be used, implement a custom validation attribute.

To demonstrate this scenario, include a ShippedDate field to the model and implement a GreaterDateAttribute attribute that will check whether the selected ShippedDate value is greater than the selected OrderDate.

Below are listed the steps for you to follow when implementing custom attributes.

  1. Create a class that inherits from ValidationAttribute and IClientValidatable, and implement the IsValid and GetClientValidationRules methods.

    Example
        [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.

    Example
        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 a Kendo UI Validator rule that will handle all inputs with the data-val-greaterdate attribute.

    Example
        @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.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.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>
    

Apply Custom Attributes in Editable Widgets

Editable widgets, such as the Kendo UI Grid and ListView, initialize the Validator internally so that to specify custom rules, you should extend the Kendo UI Validator built-in validation rules. You can also use this approach to define rules after the Kendo UI scripts are included and to use them in all views.

Example
<script>
    (function ($, kendo) {
        $.extend(true, kendo.ui.validator, {
            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");
                }
            }
        });
    })(jQuery, kendo);
</script>

@(
    Html.Kendo().Grid<OrderViewModel>()
        .Name("grid")
        .Columns(columns =>
            {
                columns.Bound(o => o.OrderDate);
                columns.Bound(o => o.ShippedDate);
                columns.Command(command => command.Edit());
            })
        .DataSource(source => source
            .Ajax()
            .Model(model => model.Id(o => o.OrderID))
            .Read("Read", "Orders")
            .Update("Update", "Orders")
        )
)

Employ jQuery Validation

Below are listed the steps for you to follow when using the jQuery validation with the Kendo UI widgets.

  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.

  3. Override the default ignore setting after including the scripts to enable validation of hidden elements. For instance, widgets like the Kendo UI DropDownList and NumericTextBox have a hidden input to keep the value.

    Example
        <script src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
        <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
        <script type="text/javascript">
            $.validator.setDefaults({
                ignore: ""
            });
        </script>
    
  4. Define the model and create the editors the same way as shown in the section on using the Kendo UI Validator with DataAnnotation attributes.

Change Widget Styles When Validation Errors Occur

The validation error classes are applied to the inputs that are validated, so the style will not be visible for widgets that use a hidden input to keep the value. To show an error style, the class can be copied to the visible wrapper by using the approach demonstrated in the kendo-input-widgets-validation sample project in this GitHub repository.

Troubleshooting

For a list of issues and solutions to common problems you may encounter while implementing the client-side validation, refer to the troubleshooting article on validation.

See Also