Skip to content

Commit 7c759a9

Browse files
committed
♻️ Extract method (#2020)
1 parent 55aff75 commit 7c759a9

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

src/lib/utils/url.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,25 @@ export function isValidUrl(rawUrl: string): boolean {
1414
return !!pattern.test(rawUrl);
1515
}
1616

17+
/**
18+
* Validates if a string is a valid URL slug.
19+
*
20+
* @param slug - The string to validate as a URL slug
21+
* @returns A boolean indicating whether the provided string is a valid URL slug
22+
*
23+
* A valid URL slug:
24+
* - Contains only lowercase letters (a-z), numbers (0-9), and hyphens (-)
25+
* - Cannot start or end with a hyphen
26+
* - Cannot contain consecutive hyphens
27+
*/
28+
export function isValidUrlSlug(slug: string): boolean {
29+
const pattern = new RegExp(
30+
'^[a-z0-9]+(-[a-z0-9]+)*$', // a-z, 0-9, and hyphen (-) allowed
31+
);
32+
33+
return !!pattern.test(slug);
34+
}
35+
1736
export function sanitizeUrl(rawUrl: string) {
1837
return xss(rawUrl);
1938
}

src/lib/zod/schema.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
// https://qiita.com/mpyw/items/886218e7b418dfed254b
55
import { z } from 'zod';
66
import { WorkBookType } from '$lib/types/workbook';
7-
import { isValidUrl } from '$lib/utils/url';
7+
import { isValidUrl, isValidUrlSlug } from '$lib/utils/url';
88

99
const INPUT_AT_LEAST_3_CHARACTERS = '3文字以上入力してください';
1010
const DELETE_UNTIL_24_CHARACTERS_ARE_LEFT = '24文字になるまで削除してください';
@@ -76,7 +76,7 @@ export const workBookSchema = z.object({
7676
.min(0, { message: '' })
7777
.max(30, { message: '30文字になるまで削除してください' }) // 問題集(カリキュラムと解法別)をURLで識別するためのオプション。a-z、0-9、(-)ハイフンのみ使用可能。例: bfs、dfs、dp、union-find、2-sat。
7878
.transform((value) => (value === '' ? undefined : value))
79-
.refine((value) => value === undefined || /^[a-z0-9]+(-[a-z0-9]+)*$/.test(value), {
79+
.refine((value) => value === undefined || isValidUrlSlug(value), {
8080
message: '半角英小文字、数字、ハイフンのみ使用可能です',
8181
})
8282
.optional(),

0 commit comments

Comments
 (0)