diff --git a/README.md b/README.md index 791fb53c5..16c90524b 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,7 @@ Validator | Description **isAscii(str)** | check if the string contains ASCII chars only. **isBase32(str [, options])** | check if the string is base32 encoded. `options` is optional and defaults to `{ crockford: false }`.
When `crockford` is true it tests the given base32 encoded string using [Crockford's base32 alternative][Crockford Base32]. **isBase58(str)** | check if the string is base58 encoded. -**isBase64(str [, options])** | check if the string is base64 encoded. `options` is optional and defaults to `{ urlSafe: false }`
when `urlSafe` is true it tests the given base64 encoded string is [url safe][Base64 URL Safe]. +**isBase64(str [, options])** | check if the string is base64 encoded. `options` is optional and defaults to `{ urlSafe: false, ignorePadding: false }`
when `urlSafe` is true it tests the given base64 encoded string is [url safe][Base64 URL Safe]. When `ignorePadding` is true it tests the given base64 encoded string without validating padding for legacy support. **isBefore(str [, date])** | check if the string is a date that is before the specified date. **isBIC(str)** | check if the string is a BIC (Bank Identification Code) or SWIFT code. **isBoolean(str [, options])** | check if the string is a boolean.
`options` is an object which defaults to `{ loose: false }`. If `loose` is set to false, the validator will strictly match ['true', 'false', '0', '1']. If `loose` is set to true, the validator will also match 'yes', 'no', and will match a valid boolean string of any case. (e.g.: ['true', 'True', 'TRUE']). diff --git a/src/lib/isBase64.js b/src/lib/isBase64.js index 02dead0f4..4d2808d34 100644 --- a/src/lib/isBase64.js +++ b/src/lib/isBase64.js @@ -17,6 +17,13 @@ export default function isBase64(str, options) { return urlSafeBase64.test(str); } + if (options.ignorePadding) { + if (str.endsWith('==')) { + return !notBase64.test(str) && len % 4 === 0; + } + return !notBase64.test(str); + } + if (len % 4 !== 0 || notBase64.test(str)) { return false; } diff --git a/test/validators.test.js b/test/validators.test.js index aa13906b0..964a82597 100644 --- a/test/validators.test.js +++ b/test/validators.test.js @@ -7202,6 +7202,37 @@ describe('Validators', () => { ], }); + test({ + validator: 'isBase64', + args: [{ ignorePadding: true }], + valid: [ + '', + 'dGVzdA==', + 'dGVzdA', + '/u/6+w==', + '/u/6+w', + 'PDw/Pz8+Pg==', + 'PDw/Pz8+Pg', + ], + invalid: [ + ' AA', + '(*2^128', + '\tAA', + '\rAA', + '\nAA', + 'This+is+a/bad+base64Url==', + '0K3RgtC_INC30LDQutC_0LTQuNGA0L7QstCw0L3QvdCw0Y8g0YHRgtGA0L7QutCw', + 'PDw_Pz8-Pg', + ], + error: [ + null, + undefined, + {}, + [], + 42, + ], + }); + for (let i = 0, str = '', encoded; i < 1000; i++) { str += String.fromCharCode(Math.random() * 26 | 97); // eslint-disable-line no-bitwise encoded = Buffer.from(str).toString('base64');