Reputation: 3
I am building a ASP.NET Mvc app. I have a Data model say User
public class user
{
public int userId {get; private set};
public string FirstName {get; set;}
}
The validation to be done is that the firstname cannot exceed 50 characters.
I have another presentation model in which i have the property FirstName too. I do not want to repeat the validation logic in both the models. I want to have it in one place and that should be it.
I can do it in a simpler way by adding a function which can be called while setting the property like
private string firstName;
public string FirstName
{
get
{
return firstName;
}
set
{
if (PropertyValidator.ValidName(value)) // assuming ValidName exists and it will throw an exception if the value is not valid
{
firstName = value;
}
}
}
But I am looking for something much simpler so that I do not need to add this for every property I need to have it validated. I looked at ValidationAttribute but then again I can validate this only from a controller (ModelState.IsValid). Since this model could be used by some other type of apps like console app, I could not choose that. But if there is a way to use the Mvc's ModelState.IsValid from outside of a controller, that would be awesome. Any suggestions are greatly appreciated.
Thanks!!
Upvotes: 0
Views: 277
Reputation: 1039468
You could take a look at FluentValidation. It is a great framework that allows you to separate the validation logic of your model from the model itself, provides easy way to unit test the validation logic and could be used in any type of application and of course seamlessly integrates with ASP.NET MVC.
Upvotes: 1
Reputation: 7667
Understand something: You, the programmer, are the only one who knows what validation is appropriate for each and every property in your program. As such, you are the one who gets to write the validation code.
Can you define a Length_Validated_String class, that validates the length of the string, and then let your various other presentation models use that class, and the validation for it, instead of reinventing the wheel each time?
Upvotes: 0