hanz
hanz

Reputation: 139

Validation using data annotation depending on referenced class

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

for e.g.

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 e.g.

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

My view is bound to AdviceUnit object.

Upvotes: 0

Views: 355

Answers (1)

uv_man
uv_man

Reputation: 224

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.

Upvotes: 1

Related Questions