Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can't apply the same data annotation twice to one property.</p> <p>I don't know what your current <code>RequiredIfAttribute</code> code looks like, but I think you will have to write another custom validator that checks the selected country and adjusts the error message accordingly.</p> <pre><code>public class PostalCodeRequiredAttribute : ValidationAttribute { private const string errorMessage = "{0} is required."; public string CountryPropertyName { get; private set; } public PostalCodeRequiredAttribute(string countryPropertyName) : base(errorMessage) { CountryPropertyName = countryPropertyName; } public override string FormatErrorMessage(string name) { return string.Format(errorMessage, name); } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null) return ValidationResult.Success; var countryPropertyInfo = validationContext.ObjectType.GetProperty(CountryPropertyName); string country = countryPropertyInfo.GetValue(validationContext.ObjectInstance, null).ToString(); // assuming your country property is bound to a string string name; if (country == "United States") name = "Zip code"; else if (country == "Canada") name = "Postal code"; else return ValidationResult.Success; // assuming postal code not required for all other countries return new ValidationResult(FormatErrorMessage(name)); } } </code></pre> <p>You would annotate like this, assuming your country property is called <code>Country</code>:</p> <pre><code>[PostalCodeRequired("Country")] public string PostalCode { get; set; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload