Posted on 3/1/2020 11:45:23 AM by Admin

Client Side validation

Remember how we do client side validation in Asp.Net MVC.The most preferred way was using unobtrusive JavaScript to bring the server side validation into the client side.

And we know, we do server side validation in Asp.net MVC with DataAnnotation Attributs.

We actually apply Data Annotations attributes to our model properties.Like required,StringLength etc.

And because of the unobtrusive & validate Jquery and DataAnnotation Attributes the validation rules merges with html helpers in the form of unobtrusive html attributes.

The same can also be applied with the kendo UI helpers and behind the scene the mechanism too is exactly same.The Kendo Validator creates validation rules based on the unobtrusive html attributes,which are generated by asp.net mvc based on the DataAnnotation Attributes applied over the Model Properties. The Validator also creates rules for the unobtrusive attributes that are generated implicitly by MVC for numbers and dates.

so lets try to implement client side validation with the help of DataAnnotation and Kendo Validator.

step 1.Create a bundle to include necessary Jquery validation files like below


  bundles.Add(new ScriptBundle("~/bundles/jqueryvalidation").Include(
                        "~/Scripts/jquery.validate.min.js",
                         "~/Scripts/jquery.validate.unobtrusive.min.js"
                        ));

step 2. Include them in your Layout page Like below. And since some of the helpers like DropDownList and Numeric Textbox etc have hidden input to keep values .We have to explicitly override the default ignore settings for such hidden elements like explained by below code.


    @Scripts.Render("~/bundles/jqueryvalidation")




step 4.Create a class in the model folder with any number of properties and apply the DataAnnotation attributes you want like below example.


  public class Movie
    {
        [Required]
        [Display(Name = "Movie")]
        public int Id { get; set; }
        [Required]
        public string MovieName { get; set; }
       
    }
    public class Director
    {
        [Required]
        [Display(Name = "Director")]
        public int Id { get; set; }
        public string  DirectorName { get; set; }
    }
  public class Person
    {
        public int Id { get; set; }
        [Required]
        [Display(Name = "Name")]
        public string Name { get; set; }
        [Required]
        [Display(Name = "Password")]
        
        public string Password { get; set; }
        public Movie Movie { get; set; }
        public List Directors { get; set; }
        [Required]
        public int Amount { get; set; }
    }

Step 4.Create an action method like below.


     public ActionResult Register()
        {
            Person person = new Person();
            person.Directors = new List() { 
            new Director(){Id=1,DirectorName="Ramesh"},
                new Director(){Id=2,DirectorName="Somesh"},
                new Director(){Id=3,DirectorName="Ganesh"},
            };
           
            return View(person);
        }

step 5.Design the form with Kendo helpers and to display the validation message use validationMessageFor helper like below.


  @using Kendo.Mvc.UI;
  @using KendoUIApp1.Models;
  @model Person
  @{
    ViewBag.Title = "Register";
   }
 <link href="~/Content/bootstrap.min.css" rel="stylesheet" />

<form action="/" method="post" id="form">
    <table class="table table-responsive-md table-bordered">
        <thead class="bg-dark text-center text-white">
            <tr>
                <th colspan="2">Registration Form</th>

            </tr>
        </thead>
        <tbody>

            <tr>
                <td>User Name</td>

                <td style="overflow-x:hidden">
                    @(Html.Kendo().TextBoxFor(p=>p.Name))
                   @(Html.ValidationMessageFor(p=>p.Name))
                </td>
            </tr>
            <tr>
                <td>Movie</td>

                <td style="overflow-x:hidden">
                    @(Html.Kendo().DropDownListFor(m => m.Movie.Id)
            .DataTextField("MovieName")
            .DataValueField("Id")
        .DataSource(source =>
        {
            source.Read(read =>
            {
                read.Action("GetMovies", "Home");
            });
        }).OptionLabel("select"))
                 
                    @(Html.ValidationMessageFor(model => model.Movie.Id))
                    
                </td>
            </tr>
            <tr>
                <td>DOB</td>

                <td style="overflow-x:hidden">
                    @(Html.Kendo().TextBoxFor(m => m.Password).HtmlAttributes(new {@Type="password" }))
                    @(Html.ValidationMessageFor(model => model.Password))
                </td>
            </tr>
            <tr>
                <td>Director</td>

                <td style="overflow-x:hidden">
                    @foreach (var item in Model.Directors)
                    {
                        @(Html.Kendo().RadioButtonFor(a => item.Id).Label(item.DirectorName).HtmlAttributes(new { @name = "mv",@type="radio" }))
                        @(Html.ValidationMessageFor(b => item.Id))
                    }
                   
                </td>
            </tr>
            <tr>
                <td>Amount</td>

                <td style="overflow-x:hidden">
                    @(Html.Kendo()
                             .NumericTextBoxFor(m=>m.Amount)
                             
                            
                    )
                    @(Html.ValidationMessageFor(m=>m.Amount))
                </td>
            </tr>
            <tr>
                <td colspan="2" style="overflow-x:hidden">
                    @(Html.Kendo().Button().Name("btnSubmit").HtmlAttributes(new { type = "submit", @class = "ml-auto k-button k-primary", style = "height:35px;width:70px;" }).Content("Save"))
                </td>
            </tr>
            <tr>
                <td colspan="2" style="overflow-x:hidden" class="status"></td>
            </tr>
        </tbody>
    </table>
</form>

Step 6. Initiate the Kendo Validator like below Script.




Run the application and press tab to check for validation.you will see all the validation is working as expected even though validation for Radiobuttons are not satisfactory.

For radio buttons create custom rules to expand kendo Validator like below .


  $("#form").kendoValidator({
            rules: {
                radio: function (input) {
                    if (input.filter("[type=radio]") && input.attr("required")) {
                        return $("#form").find("[type=radio][name=" + input.attr("name") + "]").is(":checked");
                    }
                    return true;
                }
            },
            messages: {
                radio: "This is a required field"
            }
        }).getKendoValidator();