How to handle validations involving several fields?

13 Sep 2017

How to handle validations involving several fields?

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

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

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 🐶

Think your friends would dig this article, too?

Google+
Tumblr
Preview

Know how you tear your hair out when your designer asks to make a nice form?

But what if you could implement the form experience your users deserve?

The Missing Forms Handbook of React can help you breeze through your React forms. You will learn how forms fit into React and see how to implement common form patterns.

The excerpt contains a table of contents and two chapters: on building an intuition for forms and handling various form controls.

No spam. I will occasionally send you my posts on JavaScript and React.
Preview

Know how you tear your hair out when your designer asks to make a nice form?

But what if you could implement the form experience your users deserve?

The Missing Forms Handbook of React can help you breeze through your React forms. You will learn how forms fit into React and see how to implement common form patterns.

The excerpt contains a table of contents and two chapters: on building an intuition for forms and handling various form controls.