In ASP.NET MVC 3, how can I have variable error messages when the same complex type is used in 2 model properties
I have a problem where I have a Telephone Number class defined as follows:
public class TelephoneNumber
{
[Required(ErrorMessage = "Phone number area code is required")]
public string AreaCode { get; set; }
[Required(ErrorMessage = "Phone number first 3 digits are required")]
public string PhoneFirst3 { get; set; }
[Required(ErrorMessage = "Phone number last 4 digits are required")]
public string PhoneLast4 { get; set; }
}
In my model I have 2 properties, where each of them use the TelephoneNumber data type.
[DisplayName("*Cell Phone")]
public TelephoneNumber CellPhone { get; set; }
[DisplayName("*Work Phone")]
pub开发者_开发技巧lic TelephoneNumber WorkPhone { get; set; }
I am using a validation summary and would like to modify the error message from "Phone number area code is required" to include which phone number the error message is referring to. Such as "Work Phone number area code is required" and "Cell Phone number area code is required".
Also is it possible to add a new phone number type such as:
[DisplayName("Home Phone")]
public TelephoneNumber HomePhone { get; set; }
But not have home phone be required?
This is a simplified version of my implementation but if it is possible to change or set data annotations for properties of complex types so they may have different validation annotations configured in multiple properties contained in the same model it would make life much easier when creating classes more complex than a simple phone number.
Thank you.
Is this a design issue? Telephone number, work telephone number and mobile are different classes that should probably inherit from abstract telephone number class.
This would then allow you to annotate each type of telephone number as you feel necessary. I would also specify REGEX for validating format of each number.
Thing to think about is what happens if one day I say that work telephone number should have extension as well as the number?
Lookup single responsibility principle, this might help. Good luck.
精彩评论