DEV Community

Cover image for How to handle validations involving several fields?
Gosha Arinich
Gosha Arinich

Posted on • Originally published at goshakkk.name on

 

How to handle validations involving several fields?

It’s often enough to validate each field in isolation:

  • email should contain a @;
  • password should be more than four characters.

But every once in a while, you need to validate several fields together:

  • password confirmation should match password;
  • phone number’s length depends on the country code from a separate input.

It’s hard or impossible implement that with field-level validations without unnecessarily complicating the code. However, with a simple validation architecture from the other articles, it’s pretty trivial.

A function that validates the entire form is simple:

function validate(email, password) {
  // true means invalid, so our conditions got reversed
  return {
    email: email.length === 0,
    password: password.length === 0,
  };
}
Enter fullscreen mode Exit fullscreen mode

I mean, what could be simpler? And yet, it’s very powerful. Validating several fields together is easily achievable:

function validate(email, password, passwordConfirm) {
  // true means invalid, so our conditions got reversed
  return {
    email: email.length === 0,
    password: password.length === 0,
    passwordConfirm: password !== passwordConfirm,
  };
}
Enter fullscreen mode Exit fullscreen mode

Try entering different passwords now:

JS Bin on jsbin.com

Once again, controlled inputs saved our day 🐶

This post was originally published on goshakkk.name


I blog about forms in React specifically, and other React-related things.
If you like what you see here, subscribe here to make sure you don't miss out on my next post.

Top comments (0)

The JavaScript Brief

1. Top 5 MERN STACK projects to improve your practical understanding

Boost your MERN Stack development skills by undertaking interesting beginner projects. These five engaging projects cover web applications and range from social media website applications to geo-social networking maps. Hone your understanding and apply modern techniques backed up by hands-on experience.

2. How To Optimize Your React App’s Performance

Learn the best optimizing techniques to make your React applications faster and more efficient. Focusing on the identification of performance bottlenecks and common pitfalls to avoid, these optimization strategies will keep your applications running smoothly even when faced with growing complexity.

3. A story of let, const, object mutation, and a bug in my code

In the pursuit of bug-free code, explore an incident involving a mix-up between const and let, making sure your custom code works effectively with third

party documentation. Discover best practices on program flow and learn about JavaScript's unpredictable aspects to ensure your core code is robust.