Skip to content

Instantly share code, notes, and snippets.

@js-ms
Created March 12, 2019 14:14
Show Gist options
  • Save js-ms/17e17a528a93b1eea8ef40d3c6909584 to your computer and use it in GitHub Desktop.
Save js-ms/17e17a528a93b1eea8ef40d3c6909584 to your computer and use it in GitHub Desktop.
Validation for latitude with AdonisJS/Indicative (Extending Validator)
In your start/app.js you need to register your provider inside providers, eg:
const path = require('path');
/*
|--------------------------------------------------------------------------
| Providers
|--------------------------------------------------------------------------
|
| Providers are building blocks for your Adonis app. Anytime you install
| a new Adonis specific package, chances are you will register the
| provider here.
|
*/
const providers = [
path.join(__dirname, '..', 'providers', 'LatitudeProvider'),
]
providers is the directory where you have all of your providers, and 'LatitudeProvider' is the name of your file.
const { ServiceProvider } = require('@adonisjs/fold')
class LatitudeProvider extends ServiceProvider {
async lat(data, field, message, args, get){
const value = get(data, field);
if (!value) {
return
}
let latitude = value.toString();
let result = latitude.match(/^-?([1-8]?[0-9]\.{1}\d{1,6}$|90\.{1}0{1,6}$)/);
if (!result) {
throw message
}
};
/**
* Attach context getter when all providers have
* been registered
*
* @method boot
*
* @return {void}
*/
boot () {
const Validator = use('Validator');
Validator.extend('latitude', this.lat.bind(this), 'error in latitude validation');
//
}
}
module.exports = LatitudeProvider;
const { ServiceProvider } = require('@adonisjs/fold')
class LongitudeProvider extends ServiceProvider {
async long(data, field, message, args, get){
const value = get(data, field);
if (!value) {
return
}
let longitude = value.toString();
let result = longitude.match(/^[-]?((((1[0-7][0-9])|([0-9]?[0-9]))\.(\d+))|180(\.0+)?)$/);
if (!result) {
throw message
}
};
/**
* Attach context getter when all providers have
* been registered
*
* @method boot
*
* @return {void}
*/
boot () {
const Validator = use('Validator');
Validator.extend('longitude', this.long.bind(this), 'error in longitude validation');
//
}
}
module.exports = LongitudeProvider;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment