Tuesday, 13 March 2012

MVC 3 client side TextBox Validation


1. In the model,  add attributes notation

    [Required(ErrorMessage="name is required")]
    [StringLength(50, ErrorMessage=" Max Length is 50")]
    public string Name { get; set; }
 
2. In the View, add the following before Html.BeginForm

<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>

@{ Html.EnableClientValidation(); }


3. Also in the View,  add validation message beside your TextBox
 .........
       <div class="FormInput">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
 .........

That's it !

No comments:

Post a Comment