In an ASP.NET MVC3 app I have a model that represents a user address with the typical Name, StreetAddress 1 & 2, City, Region, PostalCode and Country properties. The model currently has DataAnnotation attributes that apply to US addresses. I now need to support international addresses that will have different validation and messages depending on the Country value that is included in the model. How do I define and override the existing US DataAnnotation attribute values when the country is something like India or Japan instead of US?
For example the existing PostalCode property is defined as this:
private string _postalCode;
[StringLength(10, ErrorMessage = "Zip Code maximum length 10 characters")]
[Display(Name = "Zip Code")]
[Required(ErrorMessage = "Zip Code is required")]
[RegularExpression(@"^\d{5}(-\d{4})?$", ErrorMessage = "Invalid Zip Code")]
public string PostalCode
{
get { return _postalCode; }
set
{
if (_postalCode != value)
{
_postalCode = value;
}
}
}
I know if I had a specific India address model then the postal code would look something like this:
private string _postalCode;
[StringLength(6, ErrorMessage = "Postal Code maximum length 6 characters")]
[Display(Name = "Postal Code")]
[Required(ErrorMessage = "Postal Code is required")]
[RegularExpression(@"^([0-9]{6})$", ErrorMessage = "Invalid Postal Code")]
public string PostalCode
{
get { return _postalCode; }
set
{
if (_postalCode != value)
{
_postalCode = value;
}
}
}
How can I implement the proper client and server side validations using this model when a user selects a particular country?
I'm expecting to either do an ajax call to retrieve an updated partial view when the country is changed, or send enough data to the client so I can adjust the client side prompts and validation by modifying the appropriate attributes on the input elements and resetting validation, but how can I get the server side model to validate properly when issuing a Model.IsValid() call?