Sunday, December 6, 2009

ASP.net MVC 2 : Client-side Validation

In ASP.net MVC 2 Beta, DataAnnontation supports for validation . While creating model you can give attribute that use to support validation.

public class Student
   {
       [Required(ErrorMessage="Firstname is required field.")]
       [DisplayName("User name")]
       public string FirstName { get; set; }

      [Required(ErrorMessage = "Email is required field.")]
       [DisplayName("Email address")]

       public string Email { get; set; }

      [Required(ErrorMessage = "Fees is required field.")]      
       [DisplayName("Fees")]
       public double Fees { get; set; }
   }

Now use this model class to create view.

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication12.Models.Student>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    ViewPage2
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>

<h2>ViewPage2</h2>
<% Html.EnableClientValidation(); %>

    <% using (Html.BeginForm()) {%>

        <fieldset>
            <legend>Fields</legend>
            <p>
                <%= Html.LabelFor(model => model.FirstName) %>
                <%= Html.TextBoxFor(model => model.FirstName) %>
                <%= Html.ValidationMessageFor(model => model.FirstName) %>
            </p>
            <p>
                <%= Html.LabelFor(model => model.Email) %>
                <%= Html.TextBoxFor(model => model.Email) %>
                <%= Html.ValidationMessageFor(model => model.Email) %>
            </p>
            <p>
                <%= Html.LabelFor(model => model.Fees) %>
                <%= Html.TextBoxFor(model => model.Fees) %>
                <%= Html.ValidationMessageFor(model => model.Fees) %>
            </p>
            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>

    <% } %>

    <div>
        <%=Html.ActionLink("Back to List", "Index") %>
    </div>

</asp:Content>

To enable client side validation need to add javascript and  <% Html.EnableClientValidation(); %>.

Let me know your comment on this.

2 comments:

Henk said...

Yeah, MVC 2.0 Validation with Data Annotation is really cool. But what if I need to add some rules manually? A done some research in MVC 2.0 beta source code, and saw that it is possible: : MVC 2.0 Client validation exposed

w3c said...

Nice information, I really appreciate the way you presented.

http://www.w3cvalidation.net/