Skip to content

Commit d1b0162

Browse files
Merge pull request #27 from nullawhale/22_validate_ipv4
Feature Added - Validation an IPv4 Address
2 parents 08a6f7c + 00e4fad commit d1b0162

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed

go.sum

Whitespace-only changes.
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package rvalidation
2+
3+
import (
4+
"fmt"
5+
"regexp"
6+
)
7+
8+
// ValidateIPv4 validates a string as an ipv4 address.
9+
func ValidateIPv4(hash string) bool {
10+
class := `([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])`
11+
pattern := fmt.Sprintf(`^%[1]s\.%[1]s\.%[1]s\.%[1]s$`, class)
12+
reg := regexp.MustCompile(pattern)
13+
match := reg.MatchString(hash)
14+
15+
return match
16+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package rvalidation_test
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/patil-ashutosh/go-regex-utility/regex/rvalidation"
8+
)
9+
10+
func TestValidateIPv4(t *testing.T) {
11+
type test struct {
12+
name string
13+
hash string
14+
expectedValidity bool
15+
}
16+
17+
tests := []test{
18+
{name: "validIPv4_1", hash: "0.1.2.3", expectedValidity: true},
19+
{name: "validIPv4_2", hash: "172.16.1.2", expectedValidity: true},
20+
{name: "validIPv4_3", hash: "172.31.1.2", expectedValidity: true},
21+
{name: "validIPv4_4", hash: "192.167.1.2", expectedValidity: true},
22+
{name: "validIPv4_5", hash: "255.255.255.255", expectedValidity: true},
23+
{name: "InvalidIPv4_1", hash: "1.2.3.", expectedValidity: false},
24+
{name: "InvalidIPv4_2", hash: "1.2.256.4", expectedValidity: false},
25+
{name: "InvalidIPv4_3", hash: "1.256.3.4", expectedValidity: false},
26+
{name: "InvalidIPv4_4", hash: "1.2.3.4.5", expectedValidity: false},
27+
{name: "InvalidIPv4_5", hash: "1..3.4", expectedValidity: false},
28+
}
29+
30+
for _, tc := range tests {
31+
tc := tc
32+
t.Run(tc.name, func(t *testing.T) {
33+
isValidHash := rvalidation.ValidateIPv4(tc.hash)
34+
if isValidHash != tc.expectedValidity {
35+
t.Errorf("ValidateIPv4(%v) Failed: expected %t, actual %t",
36+
tc.hash, tc.expectedValidity, isValidHash)
37+
}
38+
})
39+
}
40+
}
41+
42+
func ExampleValidateIPv4() {
43+
fmt.Println(rvalidation.ValidateIPv4("192.168.1.2"))
44+
// Output: true
45+
}

0 commit comments

Comments
 (0)