My goal is to create a validated IP address field that will be validated against an IP address regular express or an dynamic DNS address. So basically if the user enters an valid IP address OR a valid dynamic DNS address the client will allow it to go through. I have found articles showing how to make custom fields and how to multiple attributes on a data field but nothing about how to run them as an OR condition.
Here is my code for the custom IP and Domain Name attributes:
public class IPAddressAttribute : RegularExpressionAttribute
{
public IPAddressAttribute()
: base(@"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$")
{ }
}
public class DomainNameAttribute : RegularExpressionAttribute
{
public DomainNameAttribute()
: base(@"^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$")
{ }
}
And here is my code for the field:
[Required(ErrorMessage="Wan IP is required")]
[DisplayName("Wan IP")]
[IPAddress(ErrorMessage="Enter a valid IP")]
[DomainName(ErrorMessage="Enter a valid Domain Name")]
public virtual string wan_ip { get; set; }
This code currently checks on both attributes. When I enter a valid IP address it comes back saying that I need to enter in a valid domain name, which is understandable because it’s trying to validate on both of the attributes. Because they are mutually exclusive they can never both be satisfied.
Any suggestions will be greatly appreciated!
Thanks!
Matthew
You could create a custom validation attribute, and use the two existing ones inside it. There’s an article on MSDN on creating custom attributes.