Data annotations and custom validation

asp.net-mvc data-annotations entity-framework

Question

I use data annotations to verify input data, but I'm at a loss for other creative ways to validate data.

I need to do database queries to determine if certain items already exist or not, and then show any "custom db-check errors," such as "The Companyname already exists," to the user.

How would I go about doing it in conjunction with data annotations?

I've completed all of my queries and other tasks using the entity framework and linq that came with 3.5sp1.

/M

1
8
10/10/2013 5:06:00 PM

Accepted Answer

Additional custom characteristics for data annotations

You will need to create your own attributes to do data store validation on your object instance.

Be certain that your classes inherit.System.ComponentModel.DataAnnotations.ValidationAttribute class:

public class MustNotExist: ValidationAttribute
{
    ...
}

Caution

When I wanted to confirm that the item is unique inside the data store, I encountered a similar circumstance. However, as this kind of validation should only be used for entities that are being formed and not when an entity is already returned from the data store, it was not able to do it on the entity class itself.

I came up with the idea of having a distinct interface, class, and attribute.

public interface IExternalValidator ...

class DBUniqueValidator: IExternalValidator ...

class ValidateExternallyAttribute: FilterAttribute, IActionFilter
{
    ...
    public ValidateExternallyAttribute(Type validatorType, Type entityType) ...
    ...
}

My property might be added to controller operations that receive entity arguments. Once the controller action parameters have been verified (the filter action attribute can easily access their types and values), the external validator is run against the correct parameters (provided the types are provided in the attribute definition), and ModelState errors are populated when validation is unsuccessful.

[ValidateExternally(typeof(DBUniqueValidator), typeof(User))]
public ActionResult RegisterUser(User newUser)
{
    if (!this.ModelState.IsValid)
    {
        // act accordingly - probably return some error depending on model state errors
    }
    // register new user in data store
}

By using this method, I was able to do external validation only on the activities that really required it. It also helped keep the code for my controller actions tidy and condensed. The only thing I had to do was look for model state issues.

12
7/27/2010 9:03:00 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow