Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.8 kB
1
Indexable
Never
<!DOCTYPE html>
<html>
<head>
  <title>Form Validation</title>
  <script>
    function validateForm() {
      var firstName = document.getElementById('firstName').value;
      var lastName = document.getElementById('lastName').value;
      var email = document.getElementById('email').value;
      var phone = document.getElementById('phone').value;

      // Regular expressions for validation
      var nameRegex = /^[A-Za-z]+$/;
      var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      var phoneRegex = /^\d{10}$/;

      // Validation for first name
      if (!firstName.match(nameRegex)) {
        alert('Please enter a valid first name.');
        return false;
      }

      // Validation for last name
      if (!lastName.match(nameRegex)) {
        alert('Please enter a valid last name.');
        return false;
      }

      // Validation for email
      if (!email.match(emailRegex)) {
        alert('Please enter a valid email address.');
        return false;
      }

      // Validation for phone number
      if (!phone.match(phoneRegex)) {
        alert('Please enter a valid phone number (10 digits).');
        return false;
      }

      // All fields are valid
      alert('Form submitted successfully!');
      return true;
    }
  </script>
</head>
<body>
  <form onsubmit="return validateForm()">
    <label for="firstName">First Name:</label>
    <input type="text" id="firstName" name="firstName" required><br>

    <label for="lastName">Last Name:</label>
    <input type="text" id="lastName" name="lastName" required><br>

    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required><br>

    <label for="phone">Phone:</label>
    <input type="tel" id="phone" name="phone" required><br>

    <input type="submit" value="Submit">
  </form>
</body>
</html>