Validating user input from textboxes and other form elements is a critical part of building robust web applications. Both client-side and server-side validation are essential for a good user experience as well as application security and data quality.

Native HTML Validation

Before diving into JavaScript, HTML itself provides some useful validation attributes:

Required

The required attribute makes an input mandatory before submitting a form:

<input type="text" required>

Input Types

HTML5 added input types like email, url, date etc. that validate the format:

<input type="email">
<input type="url">

Browser support is generally good for most common input types.

Number Validation

The number input validates numeric data and you can set min and max values:

<input type="number" min="18" max="99">

Pattern

The pattern attribute allows validating against regular expressions:

<input pattern="^#[A-Fa-f0-9]{6}">

This validates hex color values like #rrggbb.

Form Validation API

The Form Validation API lets you customize validation messages and check validity state of form fields.

JavaScript Validation

For more complex validation scenarios, JavaScript is needed to:

  • Check input length
  • Validate against complex formats
  • Provide specific error messages
  • Disable submitting invalid data

Key Events

Common events used for validation:

  • Submit: Best for full form validation prior to sending data
  • Keyup/Keydown: Validate each keystroke
  • Blur: Run validation when input loses focus

Let‘s look at an example with validation on submit:

// Get form and input elements
const form = document.getElementById(‘signup-form‘);
const username = document.getElementById(‘username‘);

// Validate on submit
form.addEventListener(‘submit‘, (e) => {

  // Check length
  if (username.value.length < 6) {
    e.preventDefault();
    alert(‘Username must be at least 6 characters‘);
  }

}); 

This provides a better experience than interrupting the user‘s typing to validate each character.

Validation Functions

Encapsulate validation logic into reusable functions:

function isValidName(name) {

  // Name validation logic  
  return trueOrFalse; 

}

if (!isValidName(username.value)) {
  // Show error
}

This keeps your code DRY and easier to maintain.

Regular Expressions

For rigorous validation, regular expressions are indispensable:

const phoneRegex = /^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})$/;

if (!phoneRegex.test(phoneInput.value)) { 
  // Invalid phone  
}

This regex validates common US phone formats with or without dashes.

Some great use cases include validating emails, URLs, zip codes, credit cards and more.

Disable Invalid Form Submission

An important step is preventing the form from being submitted until inputs are valid:

form.addEventListener(‘submit‘, (e) => {

  if (!inputValid) {
    // Prevent form submit
    e.preventDefault();     
  } 

});

This enforcement of validation is necessary to prevent submission of invalid or incomplete data.

User Experience Considerations

Any validation should prioritize user experience:

✅ Provide clear, actionable error messages
✅ Allow easy correction of errors
✅ Don‘t interrupt user flow unnecessarily
❌ Don‘t only provide generic alerts

Overly strict validation that blocks users excessively leads to frustration. Strike the right balance between input flexibility and quality data validation.

Client-Side vs. Server-Side Validation

Validation on the frontend provides immediate user feedback, improving efficiency and experience.

However, server-side validation is still essential as a security measure, since client-side code can be tampered with or disabled.

Ideally usage combines both client and server validation to:

  • Provide responsive validation messages (client)
  • Ensure security and data integrity (server)

Common Validation Scenarios

Here are some examples of typical textbox validation:

Passwords

Common password rules:

  • Minimum 8 characters
  • At least 1 uppercase, lowercase and special symbol

Use a regex for this:

const pwdRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})/; 

if (!pwdRegex.test(passwordInput.value)) {
  // Invalid password
}

Also consider double-checking passwords match on registration.

Email Addresses

A basic email regex:

const emailRegex = 
  /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/;

if (!emailRegex.test(emailInput.value)) {
  // Invalid email
} 

This supports common real-world email formats.

Names

For names allow unicode characters, hyphens etc:

const nameRegex = /^[a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ð ,.‘-]+$/u;

if (!nameRegex.test(nameInput.value)) {
  // Invalid characters in name
}

This supports international names. A server-side lookup against an authorized list is also beneficial for catching invalid submissions.

Addresses

Validating addresses is challenging due to variability globally. However, you can validate:

  • Minimum field lengths
  • State matches country

Google‘s Places API can also help validate address data on form submission.

Purchase Orders

PO validation depends on business rules, but often involves:

  • Globally unique ID
  • Valid status
  • Approved supplier
  • Funding source

These rules require integration with database lookups to validate effectively.

Conclusion

Robust textbox validation is crucial for positive user experience as well as application security and integrity.

Follow these leading practices for the best results:

  • Leverage native HTML validation features
  • Validate on form submit rather than excessively while typing
  • Disable form submission for invalid fields
  • Provide clear, actionable error messages
  • Balance flexibility and strict validation
  • Use regex for complex validation checks
  • Combine client-side and server-side validation

With insightful validation aligned to business needs, you can guide users to provide high quality data.

Similar Posts