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

Allow closures to be passed as sanitization rules #175

Closed Frondor closed 6 years ago

Frondor commented 6 years ago

(for Adonisjs) This way, the code is more clear, and you don't necesary need to be creating service providers for one or two extra rules

{
  latitude: parseFloat,
  longitude: Number,
  lat_lng: (val) => { // a more complex sanitization
    try {
      return JSON.parse(val)
    } catch (err) {
      return null
    }
  }
}
thetutlage commented 6 years ago

There is no need to create a service providers for a rule, you can simply add them inside your hooks file. I can allow closure, but then you will be writing this inline everywhere you need this sanitization rule.

Instead using start/hooks.js file and simply add it to the existing list.

const { hooks } = require('@adonisjs/ignitor')

hooks.after.providersBooted(() => {
  const { sanitizor } = use('Validator')

  sanitizor.lat_lng = (val) => {
  }

})

And then use it like any other rule.

Frondor commented 6 years ago

I wasn't aware of app hooks because this file wasn't created with the api boilerplate, now I see its in the docs! Thank you very much!

Anyway, there may be the case where you need sanitization for one specific case, in the whole app, so there's no need for code reuse and a simple closure might do the job, just don't encourage people to do it in the docs :) Also, personally, I feel nicer to pass parseFloat or parseInt closures directly instead of strings, that need to be later resolved to registered "sanitizors" (obviously, those closures need to be inside a try/catch block)

thetutlage commented 6 years ago

No plans to add it now, will look into it later. Thanks!