-
Notifications
You must be signed in to change notification settings - Fork 4
/
example-url-simple.ts
50 lines (44 loc) · 1.42 KB
/
example-url-simple.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import {
anyOf,
buildRegExp,
charClass,
charRange,
choiceOf,
digit,
endOfString,
oneOrMore,
optional,
startOfString,
zeroOrMore,
} from '..';
// Modified from: https://stackoverflow.com/a/2015516
test('example: simple url validation', () => {
const protocol = [choiceOf('http', 'https'), '://'];
const domainChars = charClass(charRange('a', 'z'), digit);
const domainCharsHypen = charClass(domainChars, anyOf('-'));
const domainSegment = choiceOf(
domainChars, // single char
[domainChars, zeroOrMore(domainCharsHypen), domainChars], // multi char
);
const regex = buildRegExp([
startOfString,
optional(protocol),
oneOrMore([domainSegment, '.']), // domain segment
charRange('a', 'z'), // TLD first char
oneOrMore(domainChars), // TLD remaining chars
endOfString,
]);
expect(regex).toMatchString('example.com');
expect(regex).toMatchString('beta.example.com');
expect(regex).toMatchString('http://beta.example.com');
expect(regex).toMatchString('https://beta.example.com');
expect(regex).toMatchString('a.co');
expect(regex).not.toMatchString('example');
expect(regex).not.toMatchString('aaa.a');
expect(regex).not.toMatchString('a.-a.com');
expect(regex).not.toMatchString('a.-a.com');
expect(regex).not.toMatchString('@gmail.com');
expect(regex).toEqualRegex(
/^(?:(?:http|https):\/\/)?(?:(?:[a-z\d]|[a-z\d][a-z\d-]*[a-z\d])\.)+[a-z][a-z\d]+$/,
);
});