Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Basic Data Validation Using Data Annotations: ASP.NET MVC 3

5.00/5 (2 votes)
22 Feb 2011CPOL 41.2K  
A basic introduction on how to use data annotations for validating MVC models, which solves basic validation issues

Introduction

Using data annotations for data validation in ASP.NET MVC 3.0

Background

Gives you a basic idea of how to use Data Annotations for validating MVC models which solves basic validation issues like required field, max length, regex and hidden input field.

Using the Code

Create the model first and decorate the properties with the attributes shown below, these come under the namespace System.ComponentModel.DataAnnotations.


C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace Mvc3GenericValidation.Models
 {
  #region User Model
    public class User
    {
        [Required()]
        [StringLength(6, MinimumLength = 4)]
        [RegularExpression(@"(\S)+", ErrorMessage = "White space is not allowed")]
        public string UserName { get; set; }

        [Required()]
        public string FirstName { get; set; }

        [Required()]
        public string LastName { get; set; }
        //making id as Hidden filed
        [HiddenInput(DisplayValue = false)]
        public int Id { get; set; }


    }
    #endregion
}

Create the strongly typed view using Razor view engine included in ASP.NET MVC 3.0


HTML
@model Mvc3GenericValidation.Models.User

@{
    ViewBag.Title = "CreateUser";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<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>
<h2>CreateUser</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>User</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.UserName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.UserName)
            @Html.ValidationMessageFor(model => model.UserName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.FirstName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.LastName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

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

Points of Interest

The key to note here is the referenced jquery files for unobtrusive validation, i.e. rendering of HTML5 attributes with the elements by the view engine. More information can be gathered from here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)