poppinss / indicative

Indicative is a simple yet powerful data validator for Node.js and browsers. It makes it so simple to write async validations on nested set of data.
https://indicative.adonisjs.com/
MIT License
417 stars 52 forks source link

Nullable fields #72

Closed helnokaly closed 8 years ago

helnokaly commented 8 years ago

I'm Using Lucid ORM and Indicative for validation and in my db schema I have a non required columns that defaults to null.

The problem is that validation fails when model is retrieved from database, because there is no way to skip null values in Indicative, only undefined are skipped when required rule is not set.

I believe non required fields should skip undefined or null, or adding a nullable rule.

Would like to hear your take on that kind of issue and thanks for your great work @thetutlage


// ON STORING

const post = new Post({
  content: 'Lorem ipsum dolor sit amet',
  description: undefined,
})

const rules: {
  content: 'required|string|max:255',
  description: 'string|max:255'
}

const validation = yield Validator.validateAll(post, rules) // passes

if(validation.fails()) {
  response.badRequest(validation.messages())
  return
}

yield post.save()
// ON UPDATING

const post = yield Post.find(1) // same record

const validation = yield Validator.validateAll(post, rules) // fails

if(validation.fails()) {
  response.badRequest(validation.messages())
  return
}
thetutlage commented 8 years ago

I kind of don't like the approach of Laravel nullable and here's why.

Rules should be there to validate the piece of text and not set global states which are then read by other rules and I believe that is what Laravel is doing here.

What I think will be right is passing allowNull next to string.

const rules: {
  content: 'required|string|max:255',
  description: 'string:allowNull|max:255'
}

What you think?

thetutlage commented 8 years ago

Okay went on a different path and refactored concept of modes.

Validator.setMode('strict') will throw exceptions when the value is null or an empty string.

Whereas the normal will bypass these values and one must use required rule to validate them.

helnokaly commented 8 years ago

Awesome ! the strict mode approach is much better. Thanks

thetutlage commented 8 years ago

Expect adonis-validation-provider it to be released as 3.1.0 in couple of days

helnokaly commented 8 years ago

Cool, great work you are doing there with AdonisJs Framework, keep it up.