validatorjs
validatorjs copied to clipboard
Empty Array [] won't pass to custom validator
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.
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
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.
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.
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.
any luck here ?
required_without not working for array only working with strings
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'
)