SmartCodingTips

HTML Form Validation

HTML provides built-in form validation to ensure users enter data in the correct format. You can enforce rules like required fields, input length, format constraints, and more.

Required Field

Use the required attribute to make a field mandatory before form submission.


<form>
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>
  <br><br>
  <button type="submit">Submit</button>
</form>
            

Input Constraints

Use attributes like minlength, maxlength, min, max, and pattern to control what data is accepted.


<form>
  <label for="username">Username (5-10 characters):</label>
  <input type="text" id="username" name="username" minlength="5" maxlength="10" required>
  <br><br>
  
  <label for="age">Age (18-99):</label>
  <input type="number" id="age" name="age" min="18" max="99">
  <br><br>

  <label for="zipcode">Zip Code (5 digits):</label>
  <input type="text" id="zipcode" name="zipcode" pattern="\d{5}">
  <br><br>

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

Client-Side vs Server-Side Validation

  • Client-Side: Done by the browser using HTML5 attributes and JavaScript before sending data to the server.
  • Server-Side: Performed after the form is submitted, used as a secure backup to prevent invalid data from being processed.
  • Always implement both for security and user experience.