Розробка форми з умовною логікою (Conditional Logic) на сайті
Форма з умовною логікою показує або приховує поля залежно від відповідей користувача. Замість форми з 30 полями, більшість яких нерелевантні — кожен користувач бачить тільки потрібні йому питання.
Рушій умовної логіки
interface FieldRule {
field: string; // поле, до якого застосовується правило
action: 'show' | 'hide' | 'require' | 'set_value';
conditions: Condition[];
logic: 'and' | 'or';
}
interface Condition {
field: string;
operator: 'equals' | 'not_equals' | 'contains' | 'greater_than' | 'is_empty';
value: unknown;
}
function evaluateCondition(condition: Condition, formValues: Record<string, unknown>): boolean {
const fieldValue = formValues[condition.field];
switch (condition.operator) {
case 'equals': return fieldValue === condition.value;
case 'not_equals': return fieldValue !== condition.value;
case 'contains': return String(fieldValue).includes(String(condition.value));
case 'is_empty': return !fieldValue || fieldValue === '';
case 'greater_than': return Number(fieldValue) > Number(condition.value);
default: return false;
}
}
function shouldShowField(rule: FieldRule, formValues: Record<string, unknown>): boolean {
const results = rule.conditions.map(c => evaluateCondition(c, formValues));
return rule.logic === 'and' ? results.every(Boolean) : results.some(Boolean);
}
Компонент форми з умовною логікою
function ConditionalForm({ schema, onSubmit }: Props) {
const { watch, register, handleSubmit } = useForm();
const formValues = watch();
const visibleFields = schema.fields.filter(field => {
const rule = schema.rules.find(r => r.field === field.id);
if (!rule) return true; // без правил — завжди показуємо
return rule.action === 'show'
? shouldShowField(rule, formValues)
: !shouldShowField(rule, formValues);
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<AnimatePresence>
{visibleFields.map(field => (
<motion.div
key={field.id}
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: 'auto' }}
exit={{ opacity: 0, height: 0 }}
>
<FormField field={field} register={register} />
</motion.div>
))}
</AnimatePresence>
<button type="submit">Відправити</button>
</form>
);
}
Приклад конфігурації
{
"fields": [
{ "id": "contact_type", "type": "radio", "options": ["Фізлицо", "ІП", "ООО"] },
{ "id": "company_name", "type": "text", "label": "Назва компанії" },
{ "id": "inn", "type": "text", "label": "ІНН" },
{ "id": "passport", "type": "text", "label": "Паспортні дані" }
],
"rules": [
{
"field": "company_name",
"action": "show",
"logic": "or",
"conditions": [
{ "field": "contact_type", "operator": "equals", "value": "ІП" },
{ "field": "contact_type", "operator": "equals", "value": "ООО" }
]
},
{
"field": "passport",
"action": "show",
"logic": "and",
"conditions": [
{ "field": "contact_type", "operator": "equals", "value": "Фізлицо" }
]
}
]
}
Конфігурація зберігається на сервері — логіка змінюється без деплою.
Терміни
Форма з рушієм умовної логіки та JSON-конфігурацією: 4–6 робочих днів.







