I am trying to validate a phone number which is contained over two fields.
The first field displays the area code and the other field displays the remaining phone number digits.
The requirements are:
- They are both required.
- They must be numeric.
- The area code field must be a maximum of 6 digits and the phone number field must be a maximum of 10 digits.
A single message is required to be displayed for both fields. For example, if the area code was missing but the telephone number was provided then a single message should be displayed after both fields stating "Please enter a telephone number.".
The model I currently have is similar to:
public class Customer
{
//...other fields here
public string AreaCode { get; set; }
public string PhoneNumber { get; set; }
}
I cannot implement the telephone as a single field with a regular expression or simlar.
There is a similar question to this here (and also kind of similar to here) where the answer recommends creating a custom validation attribute (in this case named MultiFieldRequired
) to specify the names of the fields which are required in the attribute. The validation attribute then uses reflection to check the values of the other properties to report if there is an error.
For example, in the case of the above model I believe I should have:
public class Customer
{
//...other fields here
public string AreaCode { get; set; }
[MultiFieldRequired("AreaCode", "PhoneNumber", ErrorMessage="Please enter a phone number")]
public string PhoneNumber { get; set; }
}
However, I have come across a small problem with the provided solution. The error returned by the custom validation attribute is only reported against the field which has the data annotation (PhoneNumber is the model above). Therefore, if the AreaCode is not entered by the user but the PhoneNumber is supplied, the error is reported against the PhoneNumber field and not the AreaCode. Additionally, if you are using the css supplied with the visual studio Internet project the supplied PhoneNumber field will be displayed in red whilst the invalid area code is displayed as white (not showing an error) so this looks a little odd.
Does anyone have a way to correct this colouring behaviour or a way that I can report an error message if either field is in error (using the correct colouring on the fields)?
Thank you in advance.