Dynamic Array data validation
Created by: sculpepper
I'm looking for an example where a dynamic array is validated. Something like below:
//! Should detect that test array is not comprised of only integers
var schema = {
test : 'required|array|integer'
}
var data = {
test : [ 0, 0, 1, 'a']
};
Thanks for any help!
Imported comments:
By thetutlage on 2015-07-10 12:00:33 UTC
You can extend indicative to write your own rule , and test what are the values inside an array , i have quoted a simple example for you.
start by writing a function for rule , which excepts some parameters passed by validation engine.
var arrayValues = function(data, field, message, args){
var self = this,
errors = [],
args = args.split(","),
type = args[0],
value = data[field];
return new Promise(function(resolve,reject){
// if field is not present , skip as required validation
// will take care of required fields
if(!value){
return resolve("validation skipped");
}
// if not an array then reject
if(!self.is.array(value)){
return reject(message);
}
// loop and push to errors array if
// any of the values is not of
// defined type
for(var i=0;i<value.length;i++){
if(typeof(value[i]) !== type){
errors.push(i);
}
}
if(errors.length > 0){
return reject(message);
}
resolve("validation passed");
});
}
next extend indicative and add above function and give it a name so that you can use it later.
indicative.extend("arrayValues","Array values are not valid",arrayValues);
use above extended rule
Thumb rule is you define rules in camelCase and use them in snake_case , so arrayValues will become array_values while consuming.
var schema = {
test: 'required|array_values:number' // you can pass any valid javascript type instead of number
};
var data = {
test: [0,0,1,'a']
}
// validation will fail
By sculpepper on 2015-07-10 16:19:34 UTC
thank you very much.