简体   繁体   中英

Validation using data annotation depending on referenced class

Can I have a different validation messages depending on the class referencing my model class...

for eg

public class AdviceUnit
{
    public Client MainClient {get;set;}

    public Client PartnerClient {get;set;}

    public List<Investments> JointInvestments {get;set;}
}

public class Client
{
    public Guid Id {get;set;}

    [Required(ErrorMessage = "ERROR MESSAGE but a different ")]
    public string FirstName {get;set;}

    [Required(ErrorMessage = "client last name is missing")]
    public string LastName {get;set;}

    [Required(ErrorMessage = "client date of birth is missing")]
    public DateTime DateOfBirth {get;set;}

}

What I really want is a different validation error message for main & partner client.

for eg

[Required(ErrorMessage = "main client first name is missing")]
[Required(ErrorMessage = "partner client first name is missing")]

My view is bound to AdviceUnit object.

Like BDH has said (sorry I wasn't stealing your answer, credit goes to BDH for posting the comment first), you could implement a custom required validation attribute.

As a proof of concept:

  1. Add a property of type 'ClientType' string to the Client class, set this to 'Main' or 'Partner'. This property will be retrieved during validation:
  public string ClientType {get; set;} 
  1. Implement custom required attribute and set a replace key:
 public class CustomRequiredAttribute : RequiredAttribute { protected override ValidationResult IsValid (object value, ValidationContext validationContext) { var instance = validationContext.ObjectInstance; var instancePropertyValue = instance.GetType().GetProperty("ClientType").GetValue(instance, null); return new ValidationResult(ErrorMessage.Replace("[replaceText]" ,instancePropertyValue.ToString())); } } 
  1. Use the CustomRequiredAttribute, using the replace key:
 [CustomRequired(ErrorMessage = "[replaceText] client first name is missing ")] public string FirstName {get;set;} 

Only caveat is that the ClientType property must be set before posting/validation occurs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM