0

My project is in ASP.NET MVC 3. In my domain I have a model object defined by Entity Framework. In order to validate properties I simply extend the generated EF object and add a metadata class which contains all my validation attributes.

[MetadataType(typeof(ContactInformationMetaData))]
public partial class ContactInformation
{

}

public class ContactInformationMetaData
{
    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }

    public string Phone { get; set; }

    [EmailValidator]
    public string Email { get; set; }
}

This works great most of the time but now I have a more complex scenario. I don't want the Phone and Email properties to be required but I want ONE of them to be required. In other words, I want to require that either email or phone or both be set, but not none.

How would I perform complex validation like this? If I create a custom validation attribute where would I put it and how would that work?

halfer
  • 19,824
  • 17
  • 99
  • 186
CatDadCode
  • 58,507
  • 61
  • 212
  • 318

2 Answers2

1

Here is another question exactly like that (even the Phone and Email example is the same): Model Validation / ASP.NET MVC 3 - Conditional Required Attribute

Community
  • 1
  • 1
Felipe Castro
  • 1,623
  • 11
  • 10
1

Check out FluentValidation:

http://fluentvalidation.codeplex.com/wikipage?title=mvc

you can easily create this type of custom validation, it's a pretty cool validation framework in general

Bassam Mehanni
  • 14,796
  • 2
  • 33
  • 41