Sobes.tech
Middle

How to implement form validation with fields name, email, phone?

sobes.tech AI

Answer from AI

Form validation with fields for name, email, and phone can be implemented on the client side using JavaScript. Here's a simple example:

<form id="myForm">
  <input type="text" id="name" placeholder="Name" required />
  <input type="email" id="email" placeholder="Email" required />
  <input type="tel" id="phone" placeholder="Phone" required />
  <button type="submit">Submit</button>
</form>

<script>
document.getElementById('myForm').addEventListener('submit', function(event) {
  const name = document.getElementById('name').value.trim();
  const email = document.getElementById('email').value.trim();
  const phone = document.getElementById('phone').value.trim();

  if (name.length === 0) {
    alert('Enter your name');
    event.preventDefault();
    return;
  }

  // Email is automatically validated thanks to type="email"
  // Additional validation can be done with a regular expression

  const phoneRegex = /^\+?\d{10,15}$/; // Example: +71234567890 or 1234567890
  if (!phoneRegex.test(phone)) {
    alert('Enter a valid phone number');
    event.preventDefault();
    return;
  }
});
</script>

This approach provides basic validation before submitting the form. For more reliable validation, data should also be checked on the server side.

How to implement form validation with fields name… - sobes.tech