Click here to Skip to main content
15,891,423 members
Articles / Desktop Programming / WPF

Validation in .NET Framework 4

Rate me:
Please Sign up or sign in to vote.
4.27/5 (7 votes)
18 Jun 2011CPOL3 min read 65.9K   787   57  
Validation Frameworks in .NET Framework 4
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel.DataAnnotations;

namespace ValidationSample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void BtnValidate_Click(object sender, EventArgs e)
        {
            Customer entity = new Customer { Title = TxtTitle.Text, FirstName = TxtFName.Text, LastName = TxtLName.Text };
            GenericValidator<ICustomer> target = new GenericValidator<ICustomer>();
            if (target.Validate(entity).Count == 0)
                MessageBox.Show("Validation Successfull - No Data Errors");
            else
            {
                IList<ValidationResult> Results = target.Validate(entity);
                foreach (ValidationResult Result in Results)
                    MessageBox.Show(Result.ErrorMessage);
            }
        }
    }

    public interface ICustomer
    {
        String FirstName { get; set; }
        string LastName { get; set; }
        string Title { get; set; }
    }

    public sealed class Customer : ICustomer
    {
        /// <summary>
        /// Gets or sets the first name.
        /// </summary>
        /// <value>The first name.</value>
        [Required(ErrorMessage = "The FirstName is a mandatory Field")]
        [StringLength(10, ErrorMessage =
        "The FirstName should not be greater than 10 characters.")]
        public string FirstName { get; set; }

        /// <summary>
        /// Gets or sets the last name.
        /// </summary>
        /// <value>The last name.</value>
        [Required(ErrorMessage = "The LastName is a mandatory Field")]
        [StringLength(10, ErrorMessage =
        "The LastName should not be greater than 10 characters.")]
        public string LastName { get; set; }

        /// <summary>
        /// Gets or sets the title.
        /// </summary>
        /// <value>The title.</value>
        [Required(ErrorMessage = "The Title is a mandatory Field")]
        public string Title { get; set; }
    }

    public sealed class GenericValidator<T>
    {
        /// <summary>
        /// Validates the specified entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        public IList<ValidationResult> Validate(T entity)
        {
            var results = new List<ValidationResult>();
            var context = new ValidationContext(entity, null, null);
            Validator.TryValidateObject(entity, context, results,true);
            return results;
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
Architect
India India
I spent some time working as a programmer and computer developer for several IT companies. I gained a lot of knowledge and experience in the process, and met some very supportive people in the industry. In May 2000' I joined LBS College for Higher studies.

I enjoyed my studies as much as academic studies can be enjoyed. I feel that I depend my understanding of computers because of them. The LBS College gives his students a high level of studying, but my main problem with it is that its tests are sometimes completely out of sync with the material that is learned, too long and/or too hard, and so students receive low grades and are frustrated. This is especially demotivating considering the fact that studying there is a lot of work.

Comments and Discussions