DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Using ASP.Net MVC Validation Attributes outside of ASP.Net

Douglas Rathbone user avatar by
Douglas Rathbone
·
Aug. 08, 12 · Interview
Like (0)
Save
Tweet
Share
5.93K Views

Join the DZone community and get the full member experience.

Join For Free

some people love them, others absolutely hate them, but if you ask me one of the coolest features in asp.net mvc is the data annotations that you use to decorate your asp.net mvc classes for validation. but one of the coolest things that came along in .net 4.0 was support for this across the whole framework – even outside of asp.net mvc!

image when working on projects outside of asp.net mvc its still just as relevant to write validation for your classes and their respective properties before you fire actions, communicate them to another class or simply add something to a database (among the 4 million other times validation can come in handy).

taking what we know from asp.net mvc, we can easily add this functionality to the public properties of any class in any project in .net 4, be it a console app, web service, silverlight, windows phone 7 – you name it.

this also means that any common libraries you use between multiple projects can have simple data annotations added in one place and validated everywhere – keeping your validation logic all in one place.

getting down to business

in the project that holds the data model classes you want to add validation to, add a reference to the framework namespace system.componentmodel.dataannotations

image

now open the class you want to add validation to.

we are going to add the following to it:

  • add a class level meta data attribute telling our validator what type of class it is
  • add your validation decorations to any properties exactly as you would in asp.net mvc

in my example below, i demonstrate how to do this with a class named person. you can see i've added a metadatatypeattribute of type person above the class declaration . i’ve also added a required field decoration to the public name property of this class.

[metadatatypeattribute(typeof(person))]
class person
{
    [required(errormessage = "you must enter a name")]
    public string name { get; set; }
}

now i've got to create a new class that we will use to validate our decorated attributes against objects – in this instance our person class above, but the same code will work for any class with the correct decorations.

create a new class in your project and call is classvalidator .

paste the following code into that file:

public class classvalidator
{
    public classvalidator(object objecttovalidate)
    {
        objectbeingvalidated = objecttovalidate;
    }

    private static object objectbeingvalidated { get; set; }

    public list<validationresult> validationerrors { get; private set; }

    public bool isvalid()
    {
        if (objectbeingvalidated != null)
        {
            validationerrors = new list<validationresult>();
            var context = new validationcontext(objectbeingvalidated, 
                null, 
                null);

            bool isvalid = validator.tryvalidateobject(objectbeingvalidated, 
                context, 
                validationerrors);

            if (!isvalid)
            {
                return false;
            }
            return true;
        }
        return false;
    }
}

and we are done - that is all we need!

using the code

to use the above example, all you need to do, is create an instance of our classvalidator and pass in the object we want to validate at initialisation.

we can then call the isvalid () method against it to find out if our class validates and a list of any validation errors will then be available in the public validationerrors property of our classvalidator.

my example below demonstrates this usage in a console application that does the following:

  • creates an instance of the example person object
  • doesn’t set any properties of this person object (so our name property will be null - and therefore invalid)
  • creates a classvalidator and passes in my newly created person, and then calls isvalid against it.
  • prints all the errors found to the console.

person p = new person();

console.writeline("attempting to validate the person object");

classvalidator validator = new classvalidator(p);

console.writeline("is object valid of not?: {0}",validator.isvalid());

foreach (var error in validator.validationerrors)
{
    console.writeline("error in person object: {0}", error.errormessage);
}

example project

i have created a simple command-line application to demonstrate the above which can be found here .

i’d love to hear of any cool ways you’ve found to use this code.

ASP.NET MVC Attribute (computing)

Published at DZone with permission of Douglas Rathbone, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • ChatGPT — The Google Killer? The Job Taker? Or Just a Fancy Chatbot?
  • TDD: From Katas to Production Code
  • Automated Performance Testing With ArgoCD and Iter8
  • API Design Patterns Review

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: