Basic Form Validations in JavaScript: Client-Side & Server-Side Validation Explained

Basic Form Validations in JavaScript: Client-Side & Server-Side Validation Explained

Basic Form Validations in JavaScript

Client-Side & Server-Side Validation Explained

Form validation ensures that user input is accurate, complete, and in the expected format before submitting data to a server. JavaScript plays an essential role in performing both Client-Side Validation and Server-Side Validation.

🔹 What is Form Validation in JavaScript?

Form validation in JavaScript ensures that users enter the correct data in web forms. It prevents incorrect or malicious data from being submitted and enhances both security and user experience.

🔹 Types of Form Validation

✅ 1. Client-Side Validation

  • Executed in the user's browser using JavaScript.
  • Provides immediate feedback without requiring a page reload.
  • Improves user experience and reduces server load.

✅ 2. Server-Side Validation

  • Occurs on the server after data submission.
  • Ensures data security and prevents malicious data entries.
  • Acts as a backup if client-side validation is bypassed.

🔹 Why is Form Validation Important?

  • Prevents invalid or incomplete data submission.
  • Enhances user experience with instant feedback.
  • Reduces server processing by catching errors early.
  • Ensures data integrity and protects against malicious attacks.

🔹 JavaScript Form Validation Example

Below is a simple JavaScript example demonstrating basic form validation:

<form id="form">
  <label>Name: <input type="text" id="name"></label>
  <label>Email: <input type="email" id="email"></label>
  <button onclick="validateForm()">Submit</button>
</form>

<script>
  function validateForm() {
    let name = document.getElementById('name').value;
    let email = document.getElementById('email').value;

    if (name === '') {
      alert('Name is required');
      return false;
    }
    if (!email.includes('@')) {
      alert('Please enter a valid email');
      return false;
    }
    alert('Form submitted successfully');
    return true;
  }
</script>

🔹 Best Practices for Form Validation

  • Always perform both client-side and server-side validation.
  • Provide clear error messages for each invalid input field.
  • Use appropriate HTML input types (e.g., `email`, `password`, `number`).
  • Prevent form submission until all fields are validated.

🔹 Let's Practice Complete Form Validation by Creating a Job Application Form

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Job Application Form</title>
  <style>
    body { font-family: Arial, sans-serif; }
    .form-container { width: 50%; margin: 50px auto; border: 1px solid #ccc; padding: 20px; border-radius: 5px; }
    fieldset { margin-bottom: 15px; padding: 10px; }
    legend { font-weight: bold; }
    label { display: block; margin-top: 10px; }
    input, select, textarea { width: 100%; margin-top: 5px; padding: 5px; }
    .error { color: red; font-size: 12px; }
    button { margin-top: 15px; padding: 8px 20px; background-color: #4CAF50; color: white; border: none; cursor: pointer; }
    button:hover { background-color: #45a049; }
    .center { text-align: center; }
  </style>
</head>
<body>
  <div class="form-container">
    <h2 class="center">Job Application Form</h2>

    <form id="jobForm" onsubmit="return validateForm()">

      <fieldset>
        <legend>Personal Information</legend>
        <label for="name">Full Name:</label>
        <input type="text" id="name" name="name">
        <span id="errorName" class="error"></span>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email">
        <span id="errorEmail" class="error"></span>
        <label for="phone">Phone Number:</label>
        <input type="tel" id="phone" name="phone">
        <span id="errorPhone" class="error"></span>
      </fieldset>

      <fieldset>
        <legend>Additional Information</legend>
        <label for="gender">Gender:</label>
        <select id="gender" name="gender">
          <option value="">Select Gender</option>
          <option value="male">Male</option>
          <option value="female">Female</option>
          <option value="other">Other</option>
        </select>
        <span id="errorGender" class="error"></span>
        <label for="resume">Upload Resume:</label>
        <input type="file" id="resume" name="resume">
        <span id="errorResume" class="error"></span>
        <label for="address">Address:</label>
        <textarea id="address" name="address" rows="3"></textarea>
        <span id="errorAddress" class="error"></span>
      </fieldset>

      <fieldset>
        <legend>Security</legend>
        <label for="password">Password:</label>
        <input type="password" id="password" name="password">
        <span id="errorPassword" class="error"></span>
        <label for="confirmPassword">Confirm Password:</label>
        <input type="password" id="confirmPassword" name="confirmPassword">
        <span id="errorConfirmPassword" class="error"></span>
      </fieldset>

      <div class="center">
        <button type="submit">Submit</button>
      </div>
    </form>
  </div>

<script>

    function validateForm() {
      const name = document.getElementById("name").value.trim();
      const email = document.getElementById("email").value.trim();
      const phone = document.getElementById("phone").value.trim();
      const gender = document.getElementById("gender").value;
      const password = document.getElementById("password").value.trim();
      const confirmPassword = document.getElementById("confirmPassword").value.trim();
      const errorName = document.getElementById("errorName");
      const errorEmail = document.getElementById("errorEmail");
      const errorPhone = document.getElementById("errorPhone");
      const errorGender = document.getElementById("errorGender");
      const errorPassword = document.getElementById("errorPassword");
      const errorConfirmPassword = document.getElementById("errorConfirmPassword");
      errorName.textContent = "";
      errorEmail.textContent = "";
      errorPhone.textContent = "";
      errorGender.textContent = "";
      errorPassword.textContent = "";
      errorConfirmPassword.textContent = "";
      let valid = true;
      if (name === "") {
        errorName.textContent = "Name is required.";
        valid = false;
      }
      if (email === "" || !email.includes("@")) {
        errorEmail.textContent = "Please enter a valid email.";
        valid = false;
      }
      if (phone === "" || phone.length < 10 || isNaN(phone)) {
        errorPhone.textContent = "Please enter a valid phone number.";
        valid = false;
      }
      if (gender === "") {
        errorGender.textContent = "Please select your gender.";
        valid = false;
      }
      if (password.length < 6) {
        errorPassword.textContent = "Password must be at least 6 characters long.";
        valid = false;
      }
      if (confirmPassword !== password) {
        errorConfirmPassword.textContent = "Passwords do not match.";
        valid = false;
      }
      if (valid) alert("Form submitted successfully!");
      return valid;
    }
</script>
</body>
</html>
Next Post Previous Post