Click here to Skip to main content
Licence CPOL
First Posted 16 Aug 2009
Views 14,124
Bookmarked 9 times

Form validation with ASP.NET MVC using the IDataErrorInfo interface

By Farooq Kaiser | 24 Aug 2009 | Technical Blog
As I already shown in my previous article Form validation with ASP.NET MVC. In this article, I will explore an alternative method of implementing validation logic. I will show you how to perform validation by using the IDataErrorInfo interface. public interface IDataErrorInfo{    // Properties    st

1

2
1 vote, 100.0%
3

4

5
3.00/5 - 1 vote
μ 3.00, σa 5.00 [?]
A Technical Blog article. View original blog here.[]

Introduction

I already talked in my previous article about form validation with ASP.NET MVC. In this article, I will explore an alternative method of implementing validation logic. I will show you how to perform validation by using the IDataErrorInfo interface.

public interface IDataErrorInfo
{
    // Properties
    string Error { get; }
    string this[string columnName] { get; }
}

We will modify the last article that implements the IDataErrorInfo interface. To implement the IDataErrorInfo interface, we must create a partial class. Our tblComment partial class is shown below:

public partial class tblComment : IDataErrorInfo
{
    private Dictionary<string, string> _errors = new Dictionary<string, string>();
    partial void OnNameChanging(string value)
    {
        if (string.IsNullOrEmpty(value.Trim()))
            _errors.Add("Name", "Name is required.");
    }
    partial void OnEmailChanging(string value)
    {
        if (string.IsNullOrEmpty(value.Trim()))
            _errors.Add("Email", "Email is required.");
    }
    partial void OnMessageChanging(string value)
    {
        if (string.IsNullOrEmpty(value.Trim()))
            _errors.Add("Message", "Message is required.");
    }
    #region IDataErrorInfo Members
    public string Error
    {
        get { return string.Empty; }
    }
    public string this[string columnName]
    {
        get
        {
            if (_errors.ContainsKey(columnName))
                return _errors[columnName];
            return string.Empty;
        }
    }
    #endregion
}

One thing to note, when the Entity Framework generates an entity class, the Entity Framework adds partial methods to the class automatically. The Entity Framework generates OnChanging and OnChanged partial methods that correspond to each property of the class. We will modify our UserCommentController class as shown below:

public class UserCommentController : Controller
{
    private CommentEntities _db = new CommentEntities();
    [AcceptVerbs("GET")]
    public ActionResult UserComment()
    {
        return View(new tblComment());
    }
    [AcceptVerbs("POST")]
    public ActionResult UserComment([Bind(Exclude = "CommentID")] 
                                     tblComment commentToCreate)
    {
        // Validate
        if (!ModelState.IsValid)
            return View();
        // Add to database
        try
        {
            _db.AddTotblComment(commentToCreate);
            _db.SaveChanges();
            return RedirectToAction("UserComment");
        }
        catch
        {
            return View();
        }
    }
}

The ASP.NET MVC framework creates the instance of the tblComment passed to the UserComment () action by using a model binder. The model binder is responsible for creating an instance of the tblComment object by binding the HTML form fields to an instance of the tblComment object. Now, I will run the project and it will display the user comment view as shown below:

Summary

In this article, we explored form validation with ASP.NET MVC using the IDataErrorInfo interface.

License

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

About the Author

Farooq Kaiser

Software Developer (Senior)
http://www.Fairnet.com
Canada Canada

Member
12+ years of complete software development life cycle experience for web based applications and multi-tier client-server desktop, primarily using LINQ, WCF, WWF, C#, ASP.NET, XML, XSLT, AJAX, Winforms,Visual Basic, JavaScript, JQuery, Google APIs, C++, VB.NET, C, ATL/COM, Open XML. Extensively involved in the requirement analysis, feasibility study, conceptualization, planning, architecture/design, configuration, development, quality assurance, implementation and release of the software products.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120209.1 | Last Updated 24 Aug 2009
Article Copyright 2009 by Farooq Kaiser
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid