loading...
Cover image for How to handle validations involving several fields?

How to handle validations involving several fields?

goshakkk profile image Gosha Arinich Originally published at goshakkk.name on ・1 min read

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,
  };
}

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,
  };
}

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.

Posted on by:

goshakkk profile

Gosha Arinich

@goshakkk

Consulting software developer: React Native, React. Market anarchist. Available for hire: http://goshakkk.name/services/mobile-mvp/

Discussion

markdown guide