From 01af709eb38decfe4ec45b1dabd028af59213b52 Mon Sep 17 00:00:00 2001 From: ebouwsema Date: Tue, 3 Jun 2014 15:19:07 -0600 Subject: [PATCH] Update to handle small steps - ie: 0.0000001 --- Dist/knockout.validation.js | 11 ++++++++--- Tests/rules-tests.js | 25 +++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/Dist/knockout.validation.js b/Dist/knockout.validation.js index 00412ba0..0f5c4bb6 100644 --- a/Dist/knockout.validation.js +++ b/Dist/knockout.validation.js @@ -803,12 +803,17 @@ kv.rules['pattern'] = { kv.rules['step'] = { validator: function (val, step) { - + var min_diff = 0.000000001; + + // in order to handle steps of .1 & .01 etc.. Modulus won't work // if the value is a decimal, so we have to correct for that if (kv.utils.isEmptyVal(val) || step === 'any') { return true; } - var dif = (val * 100) % (step * 100); - return Math.abs(dif) < 0.00001 || Math.abs(1 - dif) < 0.00001; + var valInt = val / step; + var stepInt = step * ( 1 / step); + var diff = valInt % stepInt; + + return Math.abs(diff) < min_diff || Math.abs(1 - diff) < min_diff; }, message: 'The value must increment by {0}' }; diff --git a/Tests/rules-tests.js b/Tests/rules-tests.js index 366e5397..efb48f4d 100644 --- a/Tests/rules-tests.js +++ b/Tests/rules-tests.js @@ -628,6 +628,31 @@ test('Object is NOT Valid and step is observable and isValid returns False', fun equal(testObj.isValid(), false, 'testObj is not valid'); }); +test('Object is NOT Valid with a step of 0.00000003 and isValid returns False', function () { + var testObj = ko.observable('') + .extend({ step: 0.00000003 }); + + testObj(0.00001115); + + equal(testObj(), 0.00001115, 'observable still works'); + equal(testObj.isValid(), false, 'testObj is not Valid'); +}); + + + + +test('Object is Valid with a step of 0.00000001 and isValid returns True', function () { + var testObj = ko.observable('') + .extend({ step: 0.00000002 }); + + testObj(0.00001116); + + equal(testObj(), 0.00001116, 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + + + //#endregion //#region Email Validation