c# - Apply different validation rules to the same complex property type in model -


this should have come million times now, somehow can't seem find solid floats boat.

please, consider

public class person {     public string firstname { get; set; }     public string lastname { get; set; }     public string position { get; set; } } 

which appears twice in view model

public class myviewmodel {     public person maincontact { get; set; }     public person altcontact { get; set; } } 

main contact required. alternative contact not required, if entered should validate entry. if have 2 different contact classes, described this:

public class maincontact {     [required]     [stringlength(50)]     string firstname { get; set; }      [required]     [stringlength(50)]     string lastname { get; set; }      string position { get; set; } }  public class altcontact {     [stringlength(50)]     string firstname { get; set; }      [stringlength(50)]     string lastname { get; set; }      string position { get; set; } } 

but, don't want have 2 different contact classes same properties.

i 1 set of validations applied 1 instance of person class , set of validations applied different instance of same person class. the solution has work client side validation unobtrusive js turned on. lot in advance!

update 1: added string position person , contact classes.

update 2: thank inputs. given time constraints , old ui requirements, ended having 2 separate classes. however, erik funkenbusch's alternative approach comments below. if i'll run similar situation in future, push list of objects , "add new bla" button solution. think that's way go. thanks!

as null property answer doesn't seem working you, suggest following model :

 public class maincontact: basecontact     {         [required]         [stringlength(50)]         public override string firstname { get; set; }          [required]         [stringlength(50)]         public override string lastname { get; set; }      }      public class basecontact     {         [stringlength(50)]         public virtual string firstname { get; set; }          [stringlength(50)]         public virtual string lastname { get; set; }          string position { get; set; }     } 

and make mainmodel :

public class myviewmodel {     [required]     public maincontact maincontact { get; set; }     public basecontact altcontact { get; set; } } 

you still need have 2 different models, benefit of sharing common elements through inheritance.


Comments