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

Incorrect documentation on custom Formatter #198

Closed rapodaca closed 6 years ago

rapodaca commented 6 years ago

Documentation gives this template for a custom formatter:

class MyFormatter {
  constructor () {
    this.errors = []
  }

  addError (error, field, validation, args) {
    let message = error

    if (error instanceof Error) {
      validation = 'ENGINE_EXCEPTION'
      message = error.message
    }

    this.errors.push({ field, validation, message, args })
  }

  toJSON () {
    return this.errors
  }
}

However, using this template will result in a thrown validation error even if all constraints are satisfied.

The source for VanillaValidator revealed the problem. toJSON needs to return null if there are no errors. Apparently, the framework uses the output of this method to determine if any errors are present. If null is returned, then there are no errors.

Therefore, one way to address the issue would be to update the documentation as follows:

  // must return null if no errors are present
  toJSON () {
    return this.errors.length ? this.errors : null
  }
thetutlage commented 6 years ago

Yes, you are write, we should update the docs to reflect this. Mind creating a PR for same?