test: add data validation tests
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
export function validateEmail(email: string): boolean {
|
||||
if (!email || typeof email !== 'string') {
|
||||
return false;
|
||||
}
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
return emailRegex.test(email);
|
||||
}
|
||||
|
||||
export function validatePhone(phone: string): boolean {
|
||||
if (!phone || typeof phone !== 'string') {
|
||||
return false;
|
||||
}
|
||||
const phoneRegex = /^1[3-9]\d{9}$/;
|
||||
return phoneRegex.test(phone);
|
||||
}
|
||||
|
||||
export function validatePassword(password: string): boolean {
|
||||
if (!password || typeof password !== 'string') {
|
||||
return false;
|
||||
}
|
||||
return password.length >= 8;
|
||||
}
|
||||
|
||||
export function validateUrl(url: string): boolean {
|
||||
if (!url || typeof url !== 'string') {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
new URL(url);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function validateRequired(value: unknown): boolean {
|
||||
if (value === null || value === undefined) {
|
||||
return false;
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
return value.trim().length > 0;
|
||||
}
|
||||
if (typeof value === 'number') {
|
||||
return !isNaN(value);
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return value.length > 0;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function validateLength(value: string, min: number, max: number): boolean {
|
||||
if (typeof value !== 'string') {
|
||||
return false;
|
||||
}
|
||||
return value.length >= min && value.length <= max;
|
||||
}
|
||||
|
||||
export function validateRange(value: number, min: number, max: number): boolean {
|
||||
if (typeof value !== 'number' || isNaN(value)) {
|
||||
return false;
|
||||
}
|
||||
return value >= min && value <= max;
|
||||
}
|
||||
|
||||
export function validateChineseId(id: string): boolean {
|
||||
if (!id || typeof id !== 'string') {
|
||||
return false;
|
||||
}
|
||||
const idRegex = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;
|
||||
return idRegex.test(id);
|
||||
}
|
||||
|
||||
export function validateUsername(username: string): boolean {
|
||||
if (!username || typeof username !== 'string') {
|
||||
return false;
|
||||
}
|
||||
const usernameRegex = /^[a-zA-Z0-9_]{3,20}$/;
|
||||
return usernameRegex.test(username);
|
||||
}
|
||||
Reference in New Issue
Block a user