]> git.ipfire.org Git - thirdparty/moment.git/commitdiff
Added invalidAt function to get invalid unit index
authorIskren Chernev <iskren.chernev@gmail.com>
Sun, 14 Jul 2013 07:14:05 +0000 (00:14 -0700)
committerIskren Chernev <iskren.chernev@gmail.com>
Sun, 14 Jul 2013 07:14:05 +0000 (00:14 -0700)
isValid is boolean, so its not very helpful in determining which section of
a date is wrong. inavlidAt returns the index of the broken token, where 0 is
year and 6 is millisecond.

moment.js
test/moment/is_valid.js

index c1673c1272832c9176923f2d58dce8c3bb7c4535..4e29df4755d75642200ce2faa27c49eaa7b2e50b 100644 (file)
--- a/moment.js
+++ b/moment.js
             return !!this._isValid;
         },
 
+        invalidAt: function () {
+            var i, arr1 = this._a, arr2 = (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray();
+            for (i = 6; i >= 0 && arr1[i] === arr2[i]; --i)
+                ;
+            return i;
+        },
+
         utc : function () {
             return this.zone(0);
         },
index a0e2b6028f6896e8500c7f47c468ad6da2bf8d6c..ea1c4e1ca646bd16094faa9c235e62aa91f79c28 100644 (file)
@@ -160,5 +160,18 @@ exports.is_valid = {
             test.equal(moment.utc(tests[i]).isValid(), true, tests[i] + ' should be valid');
         }
         test.done();
+    },
+
+    "invalidAt" : function (test) {
+        test.expect(7);
+        test.equal(moment([2000, 12]).invalidAt(), 1, 'month 12 is invalid: 0-11');
+        test.equal(moment([2000, 1, 30]).invalidAt(), 2, '30 is not a valid february day');
+        test.equal(moment([2000, 1, 29, 24]).invalidAt(), 3, '24 is invalid hour');
+        test.equal(moment([2000, 1, 29, 23, 60]).invalidAt(), 4, '60 is invalid minute');
+        test.equal(moment([2000, 1, 29, 23, 59, 60]).invalidAt(), 5, '60 is invalid second');
+        test.equal(moment([2000, 1, 29, 23, 59, 59, 1000]).invalidAt(), 6, '1000 is invalid millisecond');
+        test.equal(moment([2000, 1, 29, 23, 59, 59, 999]).invalidAt(), -1, '-1 if everything is fine');
+        test.done();
     }
+
 };