validations: treat `NaN` as a blank value

When a required number property is set to NaN, for example as a result
of coersion (`Number([1,2,3])`), the "presence" validation now correctly
reports an error.
This commit is contained in:
Miroslav Bajtoš 2015-04-22 19:57:48 +02:00
parent e4c602b098
commit 40eecd98c9
3 changed files with 34 additions and 0 deletions

View File

@ -628,6 +628,7 @@ function blank(v) {
if (typeof v === 'undefined') return true;
if (v instanceof Array && v.length === 0) return true;
if (v === null) return true;
if (typeof v === 'number' && isNaN(v)) return true;
if (typeof v == 'string' && v === '') return true;
return false;
}

View File

@ -149,6 +149,21 @@ describe('datatypes', function () {
coerced.nested.constructor.name.should.equal('Object');
});
it('rejects array value converted to NaN for a required property',
function(done) {
db = getSchema();
Model = db.define('RequiredNumber', {
num: { type: Number, required: true }
});
db.automigrate(function () {
Model.create({ num: [1,2,3] }, function(err, inst) {
should.exist(err);
err.should.have.property('name').equal('ValidationError');
done();
});
});
});
describe('model option persistUndefinedAsNull', function() {
var TestModel, isStrict;
before(function(done) {

View File

@ -279,6 +279,24 @@ describe('validations', function () {
u.isValid().should.be.true;
});
it('should reject NaN value as a number', function() {
User.validatesPresenceOf('age');
var u = new User();
u.isValid().should.be.false;
u.age = NaN;
u.isValid().should.be.false;
u.age = 1;
u.isValid().should.be.true;
});
it('should allow "NaN" value as a string', function() {
User.validatesPresenceOf('name');
var u = new User();
u.isValid().should.be.false;
u.name = 'NaN';
u.isValid().should.be.true;
});
it('should skip validation by property (if/unless)', function () {
User.validatesPresenceOf('domain', {unless: 'createdByScript'});