Skip to content

Commit

Permalink
Merge pull request #503 from chriso/chriso/faster-base64-validation
Browse files Browse the repository at this point in the history
Base64 validation without regular expressions
  • Loading branch information
chriso committed Feb 20, 2016
2 parents 4e06dc6 + ebcca98 commit e2ccc9f
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
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

0 comments on commit e2ccc9f

Please sign in to comment.