Monday, October 29, 2012

MVC 3 with Razor client-side validation

To Validation client Side on MVC you need to follow these steps

1. My web.config file has the following entries.
 <appSettings>
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

2.The _Layout.cshtml has the following scripts or Required pages where you wanted to validate fields

<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

3. My partial class has the following
public partial class Address
    {
        public class AddressMetaData
        {
            [DisplayName("Address Line 1")]
            [Required(ErrorMessage = "Address Line 1 is required")]
            [StringLength(100, ErrorMessage="Maximum of 100 characters")]
            public object AddressLine1 { get; set; }

            [DisplayName("Address Line 2")]
            [Required(ErrorMessage = "Address Line 2 is required")]
            [StringLength(100, ErrorMessage = "Maximum of 100 characters")]
            public object AddressLine2 { get; set; }

            [DisplayName("Address Line 3")]
            [Required(ErrorMessage = "Address Line 3 is required")]
            [StringLength(100, ErrorMessage = "Maximum of 100 characters")]
            public object AddressLine3 { get; set; }
        }
    }
 
4. And my Edit.cshtml view is so 
@model Grid.PolicyLocation
@{
ViewBag.Title = "Edit";
}
<h2>
  Edit Location
</h2>
@using (Html.BeginForm())
{
@Html.ValidationSummary("Please correct Errors")
<h3>
  Address
</h3>
<table class="noborder">
  <tr>
    <td class="noborder">
      @Html.LabelFor(model => Model.Address.AddressLine1)
    </td>
    <td class="noborder">
      @Html.EditorFor(model => model.Address.AddressLine1)
      @Html.ValidationMessageFor(model => model.Address.AddressLine1)
    </td>
  </tr>
  <tr>
    <td class="noborder">
      @Html.LabelFor(model => Model.Address.AddressLine2)
    </td>
    <td class="noborder">
      @Html.EditorFor(model => model.Address.AddressLine2)
      @Html.ValidationMessageFor(model => model.Address.AddressLine2)
    </td>
  </tr>
  <tr>
    <td class="noborder">
      @Html.LabelFor(model => Model.Address.AddressLine3)
    </td>
    <td class="noborder">
      @Html.EditorFor(model => model.Address.AddressLine3)
      @Html.ValidationMessageFor(model => model.Address.AddressLine3)
    </td>
  </tr>
</table>
} 

5. If on blur validation not work then only add this code
$(document).ready(function () {
            $('input[type=text]').blur(function () {
                $(this).valid();
            })
        })

No comments:

Post a Comment