Skip to content

Commit 5141461

Browse files
committed
feat: add ip validation solution
1 parent 11be8fb commit 5141461

File tree

3 files changed

+115
-0
lines changed

3 files changed

+115
-0
lines changed

codewars/ip-validation/README.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# IP Valitation
2+
3+
## Description
4+
5+
Write an algorithm that will identify valid IPv4 addresses in dot-decimal format. IPs should be considered valid if they consist of four octets, with values between 0 and 255, inclusive.
6+
7+
**Valid inputs examples:**
8+
9+
```txt
10+
Examples of valid inputs:
11+
1.2.3.4
12+
123.45.67.89
13+
```
14+
15+
**Invalid input examples:**
16+
17+
```txt
18+
1.2.3
19+
1.2.3.4.5
20+
123.456.78.90
21+
123.045.067.089
22+
```
23+
24+
**Notes:**
25+
26+
- Leading zeros (e.g. 01.02.03.04) are considered invalid
27+
- Inputs are guaranteed to be a single string

codewars/ip-validation/solution.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
function isValidIP(str) {
2+
const regexIP = /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$/;
3+
return regexIP.test(str);
4+
}
5+
6+
module.exports = isValidIP;
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
const isValidIP = require('./solution');
2+
3+
describe('IP Validation', () => {
4+
const testCases = [
5+
{
6+
input: '0.0.0.0',
7+
output: true,
8+
},
9+
{
10+
input: '12.255.56.1',
11+
output: true,
12+
},
13+
{
14+
input: '137.255.156.100',
15+
output: true,
16+
},
17+
{
18+
input: '',
19+
output: false,
20+
},
21+
{
22+
input: 'abc.def.ghi.jkl',
23+
output: false,
24+
},
25+
{
26+
input: '123.456.789.0',
27+
output: false,
28+
},
29+
{
30+
input: '12.34.56',
31+
output: false,
32+
},
33+
{
34+
input: '01.02.03.04',
35+
output: false,
36+
},
37+
{
38+
input: '256.1.2.3',
39+
output: false,
40+
},
41+
{
42+
input: '1.2.3.4.5',
43+
output: false,
44+
},
45+
{
46+
input: '123,45,67,89',
47+
output: false,
48+
},
49+
{
50+
input: '1e0.1e1.1e2.2e2',
51+
output: false,
52+
},
53+
{
54+
input: ' 1.2.3.4',
55+
output: false,
56+
},
57+
{
58+
input: '1.2.3.4 ',
59+
output: false,
60+
},
61+
{
62+
input: '12.34.56.-7',
63+
output: false,
64+
},
65+
{
66+
input: '1.2.3.4\n',
67+
output: false,
68+
},
69+
{
70+
input: '\n1.2.3.4',
71+
output: false,
72+
},
73+
];
74+
75+
it('should return a boolean type', () => {
76+
expect(typeof isValidIP('0.0.0.0')).toBe('boolean');
77+
});
78+
79+
it.each(testCases)('should return $output', (testCase) => {
80+
expect(isValidIP(testCase.input)).toBe(testCase.output);
81+
});
82+
});

0 commit comments

Comments
 (0)