From d2f97a9f91438e96c7b1b7826ce96aeb9827a0de Mon Sep 17 00:00:00 2001 From: Mohd Hafizuddin M Marzuki Date: Sun, 24 Mar 2024 11:17:36 +0800 Subject: [PATCH] Add `list` rule --- src/Checkers.js | 4 ++++ src/locales/en.js | 1 + src/locales/ms.js | 1 + test/test.js | 20 ++++++++++++++++++++ 4 files changed, 26 insertions(+) diff --git a/src/Checkers.js b/src/Checkers.js index 48d71da..e2552ce 100644 --- a/src/Checkers.js +++ b/src/Checkers.js @@ -132,6 +132,10 @@ export default class Checkers { return true; } + checkList(attribute, value, parameters) { + return Array.isArray(value); + } + checkBoolean(attribute, value, parameters) { return [true, false, 0, 1, '0', '1'].includes(value); } diff --git a/src/locales/en.js b/src/locales/en.js index 88bb6ec..ce5a3dd 100644 --- a/src/locales/en.js +++ b/src/locales/en.js @@ -65,6 +65,7 @@ export default { ipv4: 'The :attribute field must be a valid IPv4 address.', ipv6: 'The :attribute field must be a valid IPv6 address.', json: 'The :attribute field must be a valid JSON string.', + list: 'The :attribute field must be a list.', lowercase: 'The :attribute field must be lowercase.', lt: { array: 'The :attribute field must have less than :value items.', diff --git a/src/locales/ms.js b/src/locales/ms.js index aca1a2d..d29811e 100644 --- a/src/locales/ms.js +++ b/src/locales/ms.js @@ -65,6 +65,7 @@ export default { ipv4: 'Medan :attribute mesti alamat IPv4 yang sah.', ipv6: 'Medan :attribute mesti alamat IPv6 yang sah.', json: 'Medan :attribute mesti rentetan JSON yang sah.', + list: 'Medan :attribute mesti berbentuk senarai.', lowercase: 'Medan :attribute mesti dalam huruf kecil.', lt: { array: 'Medan :attribute mesti mempunyai kurang daripada :value item.', diff --git a/test/test.js b/test/test.js index 56a6e34..954d323 100644 --- a/test/test.js +++ b/test/test.js @@ -1487,6 +1487,26 @@ describe('Validation', () => { }); }); + describe(`Rule 'list'`, () => { + const rules = { field: 'list' }; + + it(`Passes when the field is a list`, async () => { + const validator = new Validator({ field: [1, 2, 3] }, rules); + assert(await validator.passes()); + }); + + it(`Fails when the field is not a list`, async () => { + const validator = new Validator({ field: { a: 1, b: 2, c: 3} }, rules); + assert(await validator.fails()); + + validator.setData({ field: 123 }); + assert(await validator.fails()); + + validator.setData({ field: 'abc' }); + assert(await validator.fails()); + }); + }); + describe(`Rule 'lowercase'`, () => { const rules = { field: 'lowercase' };