forked from PinSpace-Org/GistPin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidation.ts
More file actions
59 lines (52 loc) 路 1.68 KB
/
Copy pathvalidation.ts
File metadata and controls
59 lines (52 loc) 路 1.68 KB
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
51
52
53
54
55
56
57
58
59
export type ValidationResult = { valid: true } | { valid: false; error: string };
export function validateRequired(value: string, fieldName = 'Field'): ValidationResult {
if (!value || value.trim().length === 0) {
return { valid: false, error: `${fieldName} is required` };
}
return { valid: true };
}
export function validateMinLength(value: string, min: number, fieldName = 'Field'): ValidationResult {
if (value.length < min) {
return { valid: false, error: `${fieldName} must be at least ${min} characters` };
}
return { valid: true };
}
export function validateMaxLength(value: string, max: number, fieldName = 'Field'): ValidationResult {
if (value.length > max) {
return { valid: false, error: `${fieldName} must be at most ${max} characters` };
}
return { valid: true };
}
export function validateEmail(value: string): ValidationResult {
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!re.test(value)) {
return { valid: false, error: 'Enter a valid email address' };
}
return { valid: true };
}
export function validateUrl(value: string): ValidationResult {
try {
new URL(value);
return { valid: true };
} catch {
return { valid: false, error: 'Enter a valid URL' };
}
}
export function validateRange(
value: number,
min: number,
max: number,
fieldName = 'Value',
): ValidationResult {
if (value < min || value > max) {
return { valid: false, error: `${fieldName} must be between ${min} and ${max}` };
}
return { valid: true };
}
export function compose(...fns: (() => ValidationResult)[]): ValidationResult {
for (const fn of fns) {
const result = fn();
if (!result.valid) return result;
}
return { valid: true };
}