NJsonSchema icon indicating copy to clipboard operation
NJsonSchema copied to clipboard

IPv4 validation regex validates faulty ip adresses

Open vdueck opened this issue 3 years ago • 1 comments

Hi, the class IpV4FormatValidator contains a regex: private const string IpV4RegexExpression = "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"; This one supports also an ip address with only three parts, like: 192.168.178

A correct one would be: ^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$

I got this one from regular-expressions-cookbook@oreilly. Basically these are the same, but the implementation is missing the "?:(?:" at the start and "\" in the middle.

vdueck avatar Sep 09 '21 14:09 vdueck

The current regex is not correct. For instance for this input, the output should be false

string pattern = @"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
string input = "00:45:00.0";
bool isMatch = Regex.IsMatch(input, pattern);
Console.WriteLine(isMatch);

Output: true

With correct regex pattern:

string pattern = @"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
string input = "00:45:00.0";
bool isMatch = Regex.IsMatch(input, pattern);
Console.WriteLine(isMatch);

Output: false

adnan-azmat avatar Jun 02 '23 20:06 adnan-azmat