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:
parent
e4c602b098
commit
40eecd98c9
|
@ -628,6 +628,7 @@ function blank(v) {
|
||||||
if (typeof v === 'undefined') return true;
|
if (typeof v === 'undefined') return true;
|
||||||
if (v instanceof Array && v.length === 0) return true;
|
if (v instanceof Array && v.length === 0) return true;
|
||||||
if (v === null) return true;
|
if (v === null) return true;
|
||||||
|
if (typeof v === 'number' && isNaN(v)) return true;
|
||||||
if (typeof v == 'string' && v === '') return true;
|
if (typeof v == 'string' && v === '') return true;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
|
@ -149,6 +149,21 @@ describe('datatypes', function () {
|
||||||
coerced.nested.constructor.name.should.equal('Object');
|
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() {
|
describe('model option persistUndefinedAsNull', function() {
|
||||||
var TestModel, isStrict;
|
var TestModel, isStrict;
|
||||||
before(function(done) {
|
before(function(done) {
|
||||||
|
|
|
@ -279,6 +279,24 @@ describe('validations', function () {
|
||||||
u.isValid().should.be.true;
|
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 () {
|
it('should skip validation by property (if/unless)', function () {
|
||||||
User.validatesPresenceOf('domain', {unless: 'createdByScript'});
|
User.validatesPresenceOf('domain', {unless: 'createdByScript'});
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue