mikeerickson / validatorjs

A data validation library in JavaScript for the browser and Node.js, inspired by Laravel's Validator.
https://www.npmjs.com/package/validatorjs
MIT License
1.77k stars 280 forks source link

Empty Array [] won't pass to custom validator #131

Open minipai opened 8 years ago

minipai commented 8 years ago
Validator.register('fail_array', function(value, requirement, attribute) { 
    return false;
}, ':attribute Failed');
var fields = {attr: []}
var rules = {attr: 'fail_array'}
new Validator(fields, rules);

This validation will won't fail. There is use case that I want to check an array should include a value, empty array should fail as well.

garygreen commented 8 years ago

It's not clear what your trying to achieve with your fail_array rule but you need to use the array rule. Check out the tests for array-based stuff:

https://github.com/skaterdav85/validatorjs/blob/e0a41171218486adcdba06fbb6910e902ba893c2/spec/array.js https://github.com/skaterdav85/validatorjs/blob/e0a41171218486adcdba06fbb6910e902ba893c2/spec/require-rule.js#L72

garygreen commented 8 years ago

You probably want your rules as required|array|min:1 - no need for custom validation. That will check to make sure there is an array in the input and it's not empty.

minipai commented 8 years ago

No, it is not required.

I have to have a check that every item in array is number, but the field is not required. For example, if input is "", I don't want to check it. But if it is an array even is [], I want to check it.(it should fail)

Can modify input before send into validator as a workaround, but I still think [] won't pass to custom validator is quite strange.

garygreen commented 8 years ago
var Validator = require('./src/validator');

var validator = new Validator({ users: [] }, { users: 'array|min:1' });
console.log(validator.passes()); // true

In Laravel the above fails the validation rule, this seems like a bug.

pratikt-cuelogic commented 6 years ago

any luck here ?

chetanbura commented 6 years ago

required_without not working for array only working with strings

dcworldwide commented 4 years ago

I require it... because I need to write code that handles soft deletes, like the following:

Validator.register(
    'requiredArray',
    (value: Vm<any>[], requirement, attribute) => {
        console.log({ value, requirement, attribute })
        return value &&
            value.length > 0 &&
            value.filter(x => x.changeStatus != ChangeStatus.MARKED_FOR_DELETION).length > 0
    },
    'At least 1 :attribute is required'
)