38 lines
2.0 KiB
JavaScript
38 lines
2.0 KiB
JavaScript
export const LIMITS = { text: 1000, topic: 200, platform: 50, url: 500 };
|
||
const str = (v) => (typeof v === "string" ? v.trim() : "");
|
||
|
||
export function emptyCard() {
|
||
return { audience: "", positioning: "", topics: [], socials: [] };
|
||
}
|
||
|
||
// Возвращает { ok, errors: {поле: сообщение}, card }.
|
||
export function validateCard(input) {
|
||
const src = input && typeof input === "object" ? input : {};
|
||
const errors = {};
|
||
const audience = str(src.audience);
|
||
const positioning = str(src.positioning);
|
||
for (const [key, label, value] of [
|
||
["audience", "Аудитория", audience],
|
||
["positioning", "Позиционирование", positioning],
|
||
]) {
|
||
if (!value) errors[key] = `${label}: не заполнено`;
|
||
else if (value.length > LIMITS.text) errors[key] = `${label}: не больше ${LIMITS.text} знаков`;
|
||
}
|
||
|
||
const topics = (Array.isArray(src.topics) ? src.topics : []).map(str).filter(Boolean);
|
||
if (topics.length !== 3) errors.topics = "Темы: нужно ровно три";
|
||
else if (topics.some((t) => t.length > LIMITS.topic)) errors.topics = `Темы: не больше ${LIMITS.topic} знаков в каждой`;
|
||
|
||
const socials = [];
|
||
for (const s of Array.isArray(src.socials) ? src.socials : []) {
|
||
const platform = str(s?.platform);
|
||
const url = str(s?.url);
|
||
if (!platform && !url) continue; // пустая строка формы
|
||
if (!platform) errors.socials = "Соцсети: укажите название площадки";
|
||
else if (platform.length > LIMITS.platform) errors.socials = `Соцсети: название не длиннее ${LIMITS.platform} знаков`;
|
||
else if (!/^https?:\/\/\S+$/i.test(url) || url.length > LIMITS.url) errors.socials = "Соцсети: ссылка должна начинаться с http:// или https://";
|
||
socials.push({ platform, url });
|
||
}
|
||
return { ok: Object.keys(errors).length === 0, errors, card: { audience, positioning, topics, socials } };
|
||
}
|