Untitled

 avatar
unknown
plain_text
22 days ago
2.8 kB
3
Indexable
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Form Validation</title>
  <style>
    .error { color: red; font-size: 12px; }
  </style>
</head>
<body>
  <h2>Registration Form</h2>
  <form id="registrationForm">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name">
    <span id="nameError" class="error"></span><br><br>

    <label for="email">Email:</label>
    <input type="email" id="email" name="email">
    <span id="emailError" class="error"></span><br><br>

    <label for="password">Password:</label>
    <input type="password" id="password" name="password">
    <span id="passwordError" class="error"></span><br><br>

    <label for="confirmPassword">Confirm Password:</label>
    <input type="password" id="confirmPassword" name="confirmPassword">
    <span id="confirmPasswordError" class="error"></span><br><br>

    <button type="submit">Register</button>
  </form>

  <script>
    document.getElementById('registrationForm').addEventListener('submit', function(event) {
      let isValid = true;

      // Validate Name
      const name = document.getElementById('name').value.trim();
      const nameError = document.getElementById('nameError');
      if (name === '') {
        nameError.textContent = 'Name is required.';
        isValid = false;
      } else {
        nameError.textContent = '';
      }

      // Validate Email
      const email = document.getElementById('email').value.trim();
      const emailError = document.getElementById('emailError');
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(email)) {
        emailError.textContent = 'Please enter a valid email address.';
        isValid = false;
      } else {
        emailError.textContent = '';
      }

      // Validate Password
      const password = document.getElementById('password').value.trim();
      const passwordError = document.getElementById('passwordError');
      if (password.length < 6) {
        passwordError.textContent = 'Password must be at least 6 characters long.';
        isValid = false;
      } else {
        passwordError.textContent = '';
      }

      // Validate Confirm Password
      const confirmPassword = document.getElementById('confirmPassword').value.trim();
      const confirmPasswordError = document.getElementById('confirmPasswordError');
      if (confirmPassword !== password) {
        confirmPasswordError.textContent = 'Passwords do not match.';
        isValid = false;
      } else {
        confirmPasswordError.textContent = '';
      }

      // Prevent form submission if validation fails
      if (!isValid) {
        event.preventDefault();
      }
    });
  </script>
</body>
</html>
Leave a Comment