0
votes

I have a ASP.NET MVC application and want to have validation on both level - view model validation and domain model validation based on data annotation attributes. View Model validation works simple:

public class CustomerFormVM
{
    [Required]
    [Display(Name = "Name")]
    public string Name { get; set; }
    [Required]
    [Display(Name = "Street")]
    public string Street { get; set; }
    [Required]
    [Display(Name = "City")]
    public string City { get; set; }
    [Required]
    [Display(Name = "State")]
    public string State { get; set; }
}

and then call in controller:

        if (ModelState.IsValid)
        {

I have the same domain model class:

public class CustomerFormPoco
{
    [Required]
    [Display(Name = "Name")]
    public string Name { get; set; }
    [Required]
    [Display(Name = "Street")]
    public string Street { get; set; }
    [Required]
    [Display(Name = "City")]
    public string City { get; set; }
    [Required]
    [Display(Name = "State")]
    public string State { get; set; }
}

but how to validate it?

// viewmodel is CustomerFormVM object
var pocoModel = mapper.Map<CustomerFormPoco>(viewmodel);

if I don't check 'viewmodel' variable then I get 'pocoModel' variable with nullable Name, Street, City...

How to call validation and make decision depend on result?

1
Why not check the view model before you map it to the domain model? - Kyle Delaney
I'd recommend you to assume the data is already validated in the Application Layer (with your view models), instead of validating everything again. Your domain should focus on validating business rules, not data. - Alisson
jQuery Validation can handle your validation of the viewmodel on the client side. Since you are only using Required attributes that should be simple. Then if it passes then you don't have to worry about validation on the server-side. - Grizzly
This may be of use to you, and may explain why you are seeing nulls in your model even with Required annotations for strings - stackoverflow.com/questions/23939738/… - ethane

1 Answers

0
votes

How about something like this?

if (!string.IsNullOrEmpty(pocoModel.Name) && !string.IsNullOrEmpty(pocoModel.Street) && !string.IsNullOrEmpty(pocoModel.City) && !string.IsNullOrEmpty(pocoModel.State))
{
    // Code here
}

I'd probably do it with less redundancy like this:

string[] fields = new string[] { pocoModel.Name, pocoModel.Street, pocoModel.City, pocoModel.State };
bool isValid = true;
foreach (string field in fields)
{
    if (string.IsNullOrEmpty(field))
    {
        isValid = false;
        break;
    }
}
if (isValid)
{
    // Code here
}