Click here to Skip to main content
Click here to Skip to main content

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

, 22 Feb 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

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

@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)

Share

About the Author

imsauravroy
US based MNC
India India
Computer geek very much interested in learning and adopting latest and cutting edge technologies .
 
Expertise in asp.net,c#,WCF,web services,Jquery,MVC ,TTD's and design principles and patterns applying SOLID
 
Designation - Project Lead/Architect
Group type: Organisation

4 members


Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141223.1 | Last Updated 22 Feb 2011
Article Copyright 2011 by imsauravroy
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid