Proper validation messages in JavaScript

Let's learn few tips and tricks on how to write proper validation messages in JavaScript.

Simple and specific messages are better

The validation messages should be simple and specific. It should be easy to understand and should not be too long. It should be specific to the field that is being validated.

// Good
if (!username) {
  showError('Username is required.')
}

// Bad
if (!username) {
  showError('Field cannot be empty.')
}

Let's see another example of validation message for a password field.

// Good
if (password.length < 8) {
  showError('Password must be at least 8 characters long.')
}

// Bad
if (password.length < 8) {
  showError('Password too short.')
}

Provide a solution to the user

The validation message should provide a solution to the user. It should not just tell the user that something is wrong. It should also tell the user how to fix it.

// Good
if (!email) {
  showError('Enter a valid email address.')
}

// Bad
if (!email) {
  showError('Invalid email.')
}

Let's see another example of checking password complexity.

// Good
if (!isPasswordComplex(password)) {
  showError(
    'Include at least one uppercase letter, one lowercase letter, and one number.',
  )
}

// Bad
if (!isPasswordComplex(password)) {
  showError('Invalid password.')
}

Give more context through the message

The validation message should give more context to the user. It should tell the user what is wrong with the field.

// Good
if (password !== confirmPassword) {
  showError('Passwords do not match.')
}

// Bad
if (password !== confirmPassword) {
  showError('Error in password confirmation.')
}

Good validation messages helps to improve the user experience and also the developer experience. It helps the user to understand what is wrong with the field and how to fix it. It helps the developer to debug the issue quickly 🚀

Beginners to ProNode Js

Visual Guide to API Design Best Practices

This visual eBook covers essential best practices for designing robust APIs using REST principles.

This book is ideal for beginners and backend developers seeking to enhance their API design skills. However, it is not suited for those seeking an in-depth exploration of API design. This book is a quick read under 40 slides like scrolling through your instagram feed.

Visual Guide to API Design Best Practices