Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Base64 validation without regular expressions #503

Merged
merged 4 commits into from
Feb 20, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion test/validators.js
Original file line number Diff line number Diff line change
Expand Up @@ -1425,7 +1425,13 @@ describe('Validators', function () {
test({
validator: 'isBase64'
, valid: [
'TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4='
'Zg=='
, 'Zm8='
, 'Zm9v'
, 'Zm9vYg=='
, 'Zm9vYmE='
, 'Zm9vYmFy'
, 'TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4='
, 'Vml2YW11cyBmZXJtZW50dW0gc2VtcGVyIHBvcnRhLg=='
, 'U3VzcGVuZGlzc2UgbGVjdHVzIGxlbw=='
, 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuMPNS1Ufof9EW/M98FNw'+
Expand All @@ -1440,6 +1446,11 @@ describe('Validators', function () {
'12345'
, ''
, 'Vml2YW11cyBmZXJtZtesting123'
, 'Zg='
, 'Z==='
, 'Zm=8'
, '=m9vYg=='
, 'Zm9vYmFy===='
]
});
for (var i = 0, str = '', encoded; i < 1000; i++) {
Expand Down
11 changes: 9 additions & 2 deletions validator.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@

var surrogatePair = /[\uD800-\uDBFF][\uDC00-\uDFFF]/;

var base64 = /^(?:[A-Z0-9+\/]{4})*(?:[A-Z0-9+\/]{2}==|[A-Z0-9+\/]{3}=|[A-Z0-9+\/]{4})$/i;
var notBase64 = /[^A-Z0-9+\/=]/i;

var phones = {
'en-US': /^(\+?1)?[2-9]\d{2}[2-9](?!11)\d{6}$/,
Expand Down Expand Up @@ -834,7 +834,14 @@
};

validator.isBase64 = function (str) {
return base64.test(str);
var len = str.length;
if (!len || len % 4 !== 0 || notBase64.test(str)) {
return false;
}
var firstPaddingChar = str.indexOf('=');
return firstPaddingChar === -1 ||
firstPaddingChar === len - 1 ||
(firstPaddingChar === len - 2 && str[len - 1] === '=');
};

validator.isMongoId = function (str) {
Expand Down