How can JavaScript be utilized to handle user input in PHP for security confirmation messages?

When handling user input in PHP for security confirmation messages, JavaScript can be utilized to validate the input on the client-side before submitting it to the server. This can help prevent any malicious input from being sent to the server and improve the overall security of the application.

<form action="process.php" method="post" onsubmit="return validateForm()">
  <input type="text" name="username" id="username">
  <input type="password" name="password" id="password">
  <button type="submit">Submit</button>
</form>

<script>
  function validateForm() {
    var username = document.getElementById('username').value;
    var password = document.getElementById('password').value;

    if(username === '' || password === '') {
      alert('Please fill in all fields');
      return false;
    }

    return true;
  }
</script>