Skip to content

Commit

Permalink
Coerce objects created without a prototype
Browse files Browse the repository at this point in the history
Objects created with Object.create(null) do not have a toString()
method

closes #484
  • Loading branch information
chriso committed Feb 3, 2016
1 parent a297c3d commit c19e016
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
9 changes: 9 additions & 0 deletions test/validators.js
Original file line number Diff line number Diff line change
Expand Up @@ -2453,4 +2453,13 @@ describe('Validators', function () {
test({ validator: 'isWhitelisted', args: ['abcdefghijklmnopqrstuvwxyz-'], valid: ['foo', 'foobar', 'baz-foo'],
invalid: ['foo bar', 'fo.bar', 'türkçe'] });
});

it('should convert non-string input', function () {
var empty = [undefined, null, [], NaN, Object.create(null)];
empty.forEach(function (item) {
assert.equal(validator.toString(item), '');
assert(validator.isNull(item));
});
});

});
10 changes: 7 additions & 3 deletions validator.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,9 +127,13 @@
};

validator.toString = function (input) {
if (typeof input === 'object' && input !== null && input.toString) {
input = input.toString();
} else if (input === null || typeof input === 'undefined' || (isNaN(input) && !input.length)) {
if (typeof input === 'object') {
if (input !== null && typeof input.toString === 'function') {
input = input.toString();
} else {
input = '';
}
} else if (typeof input === 'undefined' || (isNaN(input) && !input.length)) {
input = '';
}
return '' + input;
Expand Down

0 comments on commit c19e016

Please sign in to comment.