"I am Saqib Jahangir. A passionate vlogger, software engineer, trainer and avid traveler with a deep love for exploring the hidden gems of our beautiful planet. With a strong foundation in Application Development, Application Architecture & Database Design and Product Management, I bring over a decade of hands-on experience building secure, scalable, and resilient web applications for a diverse range of industries."

Handle Validations for HTML Forms

A very simple Register Form with basic JavaScript validation

<html>

<head>

  <title>Simple Register Form</title>

</head>

<body>

 

<h2>Register</h2>

 

<form id="registerForm">

  Username: <input type="text" id="username"><br><br>

  Email: <input type="text" id="email"><br><br>

  Password: <input type="password" id="password"><br><br>

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

</form>

 

<script>

  const form = document.getElementById('registerForm');

 

  form.addEventListener('submit', function(event) {

    event.preventDefault(); // prevent form submission

 

    const username = document.getElementById('username').value.trim();

    const email = document.getElementById('email').value.trim();

    const password = document.getElementById('password').value.trim();

 

    if (username === '') {

      alert('Please enter username');

      return;

    }

 

    if (email === '') {

      alert('Please enter email');

      return;

    }

 

    // simple email format check

    if (!email.includes('@') || !email.includes('.')) {

      alert('Please enter a valid email');

      return;

    }

 

    if (password === '') {

      alert('Please enter password');

      return;

    }

 

    if (password.length < 6) {

      alert('Password should be at least 6 characters');

      return;

    }

 

    alert('Registration successful!');

    form.reset();

  });

</script>

 

</body>

</html>


How it works:

  • Checks if username, email, and password are filled.
  • Checks if email contains "@" and "." (basic validation).
  • Checks if password is at least 6 characters.
  • Shows alerts if any validation fails.
  • Alerts success if everything is ok and resets the form.

 


Popular Posts

Operators (Arithmetic, Comparison, Logical)

Functions (Built-in & User-defined)