HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript HTML DOM Forms

Written by RedoHub Team

JavaScript can be used to validate data in an HTML form before it is sent to a server. This improves security and provides a better experience for the user.


Basic Form Validation

You can check if a field is empty when the user clicks the "Submit" button by using the onsubmit event attribute of the form.

function validateForm() {
  let x = document.forms["myForm"]["fname"].value;
  if (x == "") {
    alert("Name must be filled out");
    return false; // Prevents form from submitting
  }
}

In the HTML, you would call this function like so:

<form name="myForm" onsubmit="return validateForm()" method="post">
  Name: <input type="text" name="fname">
  <input type="submit" value="Submit">
</form>

Accessing Form Data

The document.forms collection allows you to access any form by its name or ID, and then target specific input fields within it.

const userEmail = document.forms["register"]["email"].value;

The Constraint Validation API

Modern browsers have a built-in Constraint Validation API that provides powerful properties and methods for professional validation:

  • checkValidity(): Returns true if an input element contains valid data.
  • setCustomValidity(): Sets the validation message (useful for custom rules).
  • validationMessage: Returns the error message displayed to the user.

HTML Form Constraints

JavaScript works alongside HTML5 attributes to enforce rules:

  • disabled: Field is not processed.
  • max / min: Sets a numeric range.
  • pattern: Defines a regular expression (RegExp) pattern.
  • required: Field must be filled in.
Pro Tip: Client-side validation is great for UX, but never rely on it for security! Always perform server-side validation (PHP, Node, etc.) as well, because client-side JS can be disabled.

Key Points to Remember

  • Validate data before sending it to the server
  • Use onsubmit to trigger validation logic
  • Returning false stops the form from submitting
  • Target inputs using document.forms or standard selection methods
  • The Constraint Validation API makes complex rules easier to manage
  • Always complement JS validation with server-side checks