Spaces:
Sleeping
Sleeping
File size: 1,765 Bytes
74e7808 | 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 60 61 62 63 64 65 | interface ValidationResult {
valid: boolean;
message?: string;
normalized: string;
}
const SUPPORTED_QUERY_CHARACTERS = /^[A-Z0-9.\u3400-\u9FFF\s]+$/;
const STOCK_CODE_PATTERNS = [
/^\d{6}$/, // A-share 6-digit code
/^(SH|SZ|BJ)\d{6}$/, // A-share code with exchange prefix
/^\d{6}\.(SH|SZ|SS|BJ)$/, // A-share code with exchange suffix
/^\d{5}$/, // HK code without prefix
/^HK\d{1,5}$/, // HK-prefixed code, for example HK00700
/^\d{1,5}\.HK$/, // HK suffix format, for example 00700.HK
/^[A-Z]{1,5}(?:\.(?:US|[A-Z]))?$/, // Common US ticker format
];
/**
* Check whether the input looks like a stock code.
*/
export const looksLikeStockCode = (value: string): boolean => {
const normalized = value.trim().toUpperCase();
return STOCK_CODE_PATTERNS.some((regex) => regex.test(normalized));
};
/**
* Validate common A-share, HK, and US stock code formats.
*/
export const validateStockCode = (value: string): ValidationResult => {
const normalized = value.trim().toUpperCase();
if (!normalized) {
return { valid: false, message: '请输入股票代码', normalized };
}
const valid = looksLikeStockCode(normalized);
return {
valid,
message: valid ? undefined : '股票代码格式不正确',
normalized,
};
};
/**
* Reject obviously invalid free-text queries before they reach the backend.
*/
export const isObviouslyInvalidStockQuery = (value: string): boolean => {
const normalized = value.trim().toUpperCase();
if (!normalized || looksLikeStockCode(normalized)) {
return false;
}
if (!SUPPORTED_QUERY_CHARACTERS.test(normalized)) {
return true;
}
const hasLetters = /[A-Z]/.test(normalized);
const hasDigits = /\d/.test(normalized);
return hasLetters && hasDigits;
};
|