jfairbank / revalidate

Elegant and composable validations
http://revalidate.jeremyfairbank.com
MIT License
363 stars 20 forks source link

return `null` when no errors #48

Open smeijer opened 7 years ago

smeijer commented 7 years ago

Why not return null when there are no validation errors?

That way we could do something like:

// Usage
const dogValidator = combineValidators({
  name: composeValidators(
    isRequired,
    isAlphabetic
  )('Name'),

  age: isNumeric('Age')
});

const dog = { name: 'Tucker', age: '10' };

// style 1
const errors = dogValidator(dog);
if (errors) {
  throw new ValidationError(errors);
}

db.save(dog);

// style 2
const errors = dogValidator(dog);
if (!errors)
  db.save(dog);
}

I'm aware of the assertion helpers, but in my opinion they shouldn't be really necessary.

jfairbank commented 7 years ago

Hi, @smeijer.

This isn't a bad idea. Out-of-the-box interop with redux-form is very important, and it seems to support a validate function that returns a falsy value. However, this would be a breaking change, so I'm hesitant to immediately change this. Maybe some opt-in behavior for now via an option until the next major release would be a good middle ground.

So something like this:

const dogValidator = combineValidators({
  name: composeValidators(
    isRequired,
    isAlphabetic
  )('Name'),

  age: isNumeric('Age')
}, { nullWhenValid: true });
smeijer commented 7 years ago

You're totally right about the breaking change. Your solution sounds perfect to me.

The developers that depend on an empty object being present, can easily use the || operator to force this result. That's actually a pretty usual convention in the world of javascript. So it should feel familiar to them.

const errors = dogValidator(dog) || {}; // errors = {} when dogValidator returns null

Your solution of the extra option in the next release, and changing the default on the next major sounds awesome. Thanks!