refactor: improve domainRegex

This commit is contained in:
moonrailgun 2024-04-26 00:37:06 +08:00
parent 5767d4595b
commit 8c64481320
5 changed files with 30 additions and 2 deletions

View File

@ -582,6 +582,10 @@ importers:
dayjs:
specifier: 1.11.10
version: 1.11.10
devDependencies:
vitest:
specifier: ^1.2.1
version: 1.2.1(@types/node@18.17.12)(happy-dom@14.7.1)
website:
dependencies:

View File

@ -1,6 +1,6 @@
import { RuleObject } from 'antd/es/form';
import { z } from 'zod';
import { hostnameRegex, slugRegex } from '@tianji/shared';
import { hostnameRegex, slugRegex, domainRegex } from '@tianji/shared';
type Validator = (
rule: RuleObject,
@ -24,7 +24,7 @@ export const domainValidator: Validator = (rule, value, callback) => {
return;
}
z.string().regex(hostnameRegex).parse(value);
z.string().regex(domainRegex).parse(value);
callback();
} catch (err) {
callback('Not valid, it should be domain, for example: example.com');

View File

@ -10,6 +10,7 @@
},
"scripts": {
"check:type": "tsc --noEmit --skipLibCheck --module esnext",
"test": "vitest",
"build": "concurrently npm:build:cjs npm:build:esm",
"build:cjs": "tsc --module commonjs --outDir ./dist/cjs",
"build:esm": "tsc --module esnext --outDir ./dist/esm",
@ -19,5 +20,8 @@
"author": "moonrailgun <moonrailgun@gmail.com>",
"dependencies": {
"dayjs": "^1.11.9"
},
"devDependencies": {
"vitest": "^1.2.1"
}
}

View File

@ -0,0 +1,17 @@
import { describe, expect, test } from 'vitest';
import { domainRegex } from './regex';
describe('regex', () => {
describe('domainRegex', () => {
test.each([
'555.123.4567',
'www.demo.com',
'bar.ba.test.co.uk',
'g.com',
'xn--d1ai6ai.xn--p1ai',
'foodemo.net',
])('test: %s', (input) => {
expect(domainRegex.test(input)).toBe(true);
});
});
});

View File

@ -2,3 +2,6 @@ export const hostnameRegex =
/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9])$/;
export const slugRegex = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
export const domainRegex =
/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$/;