An alternative is to use a method of its own, such as this to validate IP in the form of Ipv4:
public bool ValidateIPv4(string ipString)
{
if (String.IsNullOrWhiteSpace(ipString))
{
return false;
}
string[] splitValues = ipString.Split('.');
if (splitValues.Length != 4)
{
return false;
}
byte tempForParsing;
return splitValues.All(r => byte.TryParse(r, out tempForParsing));
}
Implementation:
string ip1 = "q.1;00.1.";
string ip2 = "127.0.0.1";
string ip3 = "999.0.0.2";
Console.WriteLine(ValidateIPv4(ip1));
Console.WriteLine(ValidateIPv4(ip2));
Console.WriteLine(ValidateIPv4(ip3));
Exit:
False
True
False
This method is an alternative to Ipadress.Tryparse. which has limitations and may return incorrect results. It is also easy to maintain since it has only three rules to determine if the IP address is valid.
Source.
([0-9]{1,3}\.){3}[0-9]{1,3}
-- protect the.
– JJoao
Victorfreitas, what are empty characters? And you want empty characters in the IP?
– JJoao
Sorry Joao, the right thing would be to accept the empty field, in case the user gives up filling the field.
– Victor Freitas