Dev.to WebDev 🛠 Dev 👁 0 📖 1 min read

Building Robust Health-Tech Tools: Handling Data Validation in JS

When building practical tools like a Dog Chocolate Toxicity Calculator, the math is simple—but the UX (user experience) validation is the real challenge. Users often input data rapidly in stressful situations (e.g., "My

When building practical tools like a Dog Chocolate Toxicity Calculator, the math is simple—but the UX (user experience) validation is the real challenge. Users often input data rapidly in stressful situations (e.g., "My dog just ate this!"). Your code needs to handle invalid inputs gracefully while providing clear, authoritative results.

The Problem: Defensive Programming

In a production-ready toxicity calculator, we cannot assume the user will input clean numbers. We need a validation layer that protects against NaN values, negative numbers, or empty strings.

The Implementation

Here is how to structure a defensive calculation function that sanitizes inputs before processing the logic:

/**
 * Defensive Toxicity Calculator
 * @param {string|number} weight - Dog weight in lbs
 * @param {string} type - Chocolate category
 * @param {string|number} amount - Amount in oz
 */
function calculateToxicitySafely(weight, type, amount) {
  // 1. Sanitize Inputs
  const w = parseFloat(weight);
  const a = parseFloat(amount);

  if (isNaN(w) || isNaN(a) || w <= 0 || a <= 0) {
    throw new Error("Please enter valid positive numbers for weight and amount.");
  }

  // 2. Define Potency (mg of methylxanthines per oz)
  const POTENCY_MAP = {
    white: 0.25,
    milk: 60,
    dark: 150,
    bakers: 450,
    cocoa: 800
  };

  const potency = POTENCY_MAP[type.toLowerCase()] || 0;

  // 3. Perform Math
  const weightKg = w * 0.453592;
  const totalMg = potency * a;
  const mgPerKg = totalMg / weightKg;

  // 4. Return formatted severity
  return {
    toxicityLevel: mgPerKg > 60 ? 'Severe' : mgPerKg > 20 ? 'Moderate' : 'Low',
    mgPerKg: mgPerKg.toFixed(2)
  };
}

try {
  console.log(calculateToxicitySafely(20, 'milk', 5));
} catch (e) {
  console.error(e.message);
}

Why This Matters

By implementing strict validation and error handling, you ensure that even when a user is panicking, the calculator provides a reliable output rather than crashing or returning undefined.

We have applied this pattern to a live Dog Chocolate Toxicity Calculator. It demonstrates how to wrap this logic into a reactive UI, ensuring that the critical "Go to the Vet" message is unmistakable when the calculation hits the danger threshold.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.