validatorjs icon indicating copy to clipboard operation
validatorjs copied to clipboard

Empty Array [] won't pass to custom validator

Open minipai opened this issue 7 years ago • 7 comments

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.

minipai avatar Sep 15 '16 12:09 minipai

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 avatar Sep 15 '16 12:09 garygreen

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.

garygreen avatar Sep 15 '16 12:09 garygreen

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.

minipai avatar Sep 15 '16 14:09 minipai

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.

garygreen avatar Sep 15 '16 14:09 garygreen

any luck here ?

pratikt-cuelogic avatar Aug 01 '18 06:08 pratikt-cuelogic

required_without not working for array only working with strings

chetanbura avatar Aug 01 '18 06:08 chetanbura

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'
)

dcworldwide avatar Jan 16 '20 09:01 dcworldwide