feat: add validations & translations

This commit is contained in:
divocat
2025-10-27 13:06:33 +02:00
parent d4b3377d68
commit f1a6ff3469
9 changed files with 488 additions and 210 deletions

View File

@@ -16,6 +16,7 @@ const invalidUrls = [
['Unsupported protocol (ftp)', 'ftp://example.com'],
['Unsupported protocol (ws)', 'ws://example.com'],
['Empty string', ''],
['Without tld', 'https://google'],
];
describe('validateUrl', () => {

View File

@@ -2,19 +2,31 @@ import { ValidationResult } from './types';
export function validateUrl(
url: string,
protocols: string[] = ['http:', 'https:'],
protocols = ['http:', 'https:'],
): ValidationResult {
try {
const parsedUrl = new URL(url);
if (!protocols.includes(parsedUrl.protocol)) {
return {
valid: false,
message: `${_('URL must use one of the following protocols:')} ${protocols.join(', ')}`,
};
}
return { valid: true, message: _('Valid') };
} catch (_e) {
if (!url.length) {
return { valid: false, message: _('Invalid URL format') };
}
const hasValidProtocol = protocols.some((p) => url.indexOf(p + '//') === 0);
if (!hasValidProtocol)
return {
valid: false,
message:
_('URL must use one of the following protocols:') +
' ' +
protocols.join(', '),
};
const regex = new RegExp(
`^(?:${protocols.map((p) => p.replace(':', '')).join('|')})://` +
`(?:[A-Za-z0-9-]+\\.)+[A-Za-z]{2,}(?::\\d+)?(?:/[^\\s]*)?$`,
);
if (regex.test(url)) {
return { valid: true, message: _('Valid') };
}
return { valid: false, message: _('Invalid URL format') };
}