Skip to content

Commit 775480b

Browse files
committed
fix: common string patterns
1 parent 3bcae49 commit 775480b

File tree

2 files changed

+52
-5
lines changed

2 files changed

+52
-5
lines changed

src/schemas/user.ts

+2-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
import * as yup from "yup"
1+
import { alphaString } from "../utils/schema"
22

3-
export const firstNameSchema = yup
4-
.string()
5-
.max(150)
6-
.matches(/^[a-zA-Z]*$/, "can only contain only letters characters")
3+
export const firstNameSchema = alphaString().max(150)

src/utils/schema.ts

+50
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ import {
99
type Schema,
1010
type TypeFromShape,
1111
type ValidateOptions,
12+
type StringSchema,
13+
string as YupString,
1214
} from "yup"
1315

1416
export type _<T> = T extends {}
@@ -30,6 +32,54 @@ export type ObjectSchemaFromShape<Shape extends ObjectShape> = ObjectSchema<
3032
""
3133
>
3234

35+
// -----------------------------------------------------------------------------
36+
// Limited Character Sets
37+
// -----------------------------------------------------------------------------
38+
39+
export function limitCharSet(
40+
charSet: string,
41+
message: string,
42+
schema: StringSchema = YupString(),
43+
) {
44+
return schema.matches(new RegExp(`^[${charSet}]*$`), message)
45+
}
46+
47+
export function alphaString(schema: StringSchema = YupString()) {
48+
return limitCharSet(
49+
"a-zA-Z",
50+
"can only contain alpha characters (a-z, A-Z)",
51+
schema,
52+
)
53+
}
54+
55+
export function lowercaseAlphaString(schema: StringSchema = YupString()) {
56+
return limitCharSet(
57+
"a-z",
58+
"can only contain lowercase alpha characters (a-z)",
59+
schema,
60+
)
61+
}
62+
63+
export function uppercaseAlphaString(schema: StringSchema = YupString()) {
64+
return limitCharSet(
65+
"A-Z",
66+
"can only contain uppercase alpha characters (A-Z)",
67+
schema,
68+
)
69+
}
70+
71+
export function numericString(schema: StringSchema = YupString()) {
72+
return limitCharSet("0-9", "can only contain numbers (0-9)", schema)
73+
}
74+
75+
export function alphanumericString(schema: StringSchema = YupString()) {
76+
return limitCharSet(
77+
"a-zA-Z0-9",
78+
"can only contain alphanumeric characters (a-z, A-Z, 0-9)",
79+
schema,
80+
)
81+
}
82+
3383
// -----------------------------------------------------------------------------
3484
// Try Validate Sync
3585
// -----------------------------------------------------------------------------

0 commit comments

Comments
 (0)