EuroForm

by Imri Paloja

HTML

<link
  rel="stylesheet"
  href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css"
/>
<link
  rel="stylesheet"
  href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css"
/>

<div class="main container">
  <form id="myForm">
    <label for="fname">First name:</label><br />
    <input type="text" id="fname" name="fname" required /><br />
    <label for="lname">Last name:</label><br />
    <input
      type="text"
      id="lname"
      name="lname"
      required
      minlength="8"
    /><br /><br />
    <input type="submit" value="Submit" />
  </form>
</div>

CSS

html,
body {
  color: #454545;
}

.main.container {
  margin-top: 5%;
}

input,
button,
.button {
  width: 100%;
}

JavaScript

/**
 * Validates all input fields in a form with the specified ID.
 * @param {string} formId - The ID of the form to validate.
 * @returns {Object} - An object with `isValid` (boolean) and `errors` (object of error messages).
 */
function validateForm(formId) {
  const form = document.getElementById(formId);
  if (!form) {
    console.error(`Form with ID "${formId}" not found.`);
    return {
      isValid: false,
      errors: { form: `Form with ID "${formId}" not found.` },
    };
  }

  const inputs = form.querySelectorAll('input, textarea, select');
  const errors = {};
  let isValid = true;

  inputs.forEach((input) => {
    const name = input.name || input.id;
    if (!name) return; // Skip inputs without a name or ID

    // Check for required fields
    if (input.required && !input.value.trim()) {
      errors[name] = 'This field is required.';
      isValid = false;
      return;
    }

    // Check for email format
    if (
      input.type === 'email' &&
      !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(input.value)
    ) {
      errors[name] = 'Please enter a valid email address.';
      isValid = false;
      return;
    }

    // Check for minimum length
    if (input.minLength && input.value.length < input.minLength) {
      errors[name] = `Minimum length is ${input.minLength} characters.`;
      isValid = false;
      return;
    }

    // Check for maximum length
    if (input.maxLength && input.value.length > input.maxLength) {
      errors[name] = `Maximum length is ${input.maxLength} characters.`;
      isValid = false;
      return;
    }

    // Check for pattern validation (regex)
    if (input.pattern && !new RegExp(input.pattern).test(input.value)) {
      errors[name] = input.title || 'Invalid format.';
      isValid = false;
      return;
    }
  });

  return { isValid, errors };
}

const form = document.getElementById('myForm');
form.addEventListener('submit', (event) => {
 ...