Question

I'm trying to wrap my head around validating user input and validating a business object. Let's say I am working with a Customer object. It is has the following properties: CustomerId, FirstName and LastName. FirstName and LastName are required, and their length cannot be more than 50 characters long.

I am using ASP.NET MVC 3. I am also experimenting with Fluent Validation (but does not have to be this validation framework).

When I am on the Create customer view, I pass the view a CustomerViewModel:

[Validator(typeof(CustomerViewModelValidator))]
public class CustomerViewModel
{
   public string FirstName { get; set; }
   public string LastName { get; set; }
}

In CustomerViewModelValidator I set the required rules for the validation as described above. This all validates fine on the view. Now I have a question. In my application I have a service layer, here I want to apply all application logic. Lets say I want to Save a new customer then I will have a Save customer method in CustomerService which calls CustomerRepository's Save method.

I might have another application (other than the web app described above) that will make use of my service layer. So this is going to mean I am going to have to validate a Customer object if one is created. The following questions arise:

  • Do I need to validate a Customer object in the CustomerService as well to check FirstName and LastName?
  • Would it be better to create a new validator class to validate the Customer class? Or should I share it?
  • Do I need to validate CustomerId as well? I mean it should be greater than zero, but how would I valid a new Customer where Id is 0?

If anyone can share some insight/articles into this it would appreciated.

I would love to add some business rules as well, where would this be? Where and how do I implement business rules?

Was it helpful?

Solution

Do I need to validate a Customer object in the CustomerService as well to check FirstName and LastName?

There might be different opinions on this matter and mine is that if you are creating a reusable service then it would be more correct to validate the Customer object at the service level.

Would it be better to create a new validator class to validate the Customer class? Or should I share it?

You should create a new validator. Remember that CustomerViewModel and Customer are two different classes. The view model is specific to a given view and might contain a subset or a superset of properties of the model class. The validation at the service layer should validate only business rules.If you are using SQL server this validation could even be performed at the database level (by setting the length of the columns) and an exception will be thrown if some of those business rules is violated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top