From cec7f6da4094d99b10de38b24bfad1eb5aaea29f Mon Sep 17 00:00:00 2001 From: delixfe Date: Wed, 29 Aug 2012 17:34:37 +0200 Subject: [PATCH 001/165] added unit test 'Nested grouping finds items in observableArrays - observable' --- Tests/validation-tests.js | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Tests/validation-tests.js b/Tests/validation-tests.js index d1d1e04f..b3bac4b3 100644 --- a/Tests/validation-tests.js +++ b/Tests/validation-tests.js @@ -896,6 +896,15 @@ test('Nested Grouping works - Not Observable', function () { equals(errors().length, 3, 'Grouping correctly finds 3 invalid properties'); }); +test('Nested grouping finds items in observableArrays - observable', function () { + var vm = { array: ko.observableArray( [ { one: ko.observable().extend( { required: true } ) } ]) }; + + var errors = ko.validation.group(vm, { deep: true, observable: true }); + + equals(errors().length, 1, 'Grouping finds property on object in observableArray'); + +}); + test('Issue #31 - Recursively Show All Messages', function () { var vm = { one: ko.observable().extend({ required: true }), From afb5c1c831e55be2a52e57cf0b6a2dafa24994c3 Mon Sep 17 00:00:00 2001 From: delixfe Date: Thu, 30 Aug 2012 20:12:06 +0200 Subject: [PATCH 002/165] extended group with a new option live which enables group to retraverse the viewmodel if a change in an observableArray is detected --- Src/knockout.validation.js | 15 ++++++++++++++- Tests/validation-tests.js | 19 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/Src/knockout.validation.js b/Src/knockout.validation.js index 64001c7e..e3fef9ac 100644 --- a/Src/knockout.validation.js +++ b/Src/knockout.validation.js @@ -35,7 +35,8 @@ errorMessageClass: 'validationMessage', // class to decorate error message grouping: { deep: false, //by default grouping is shallow - observable: true //and using observables + observable: true, //and using observables + live: false //react to changes to observableArrays if observable === true } }; @@ -132,6 +133,10 @@ if (val === "") { return true; } + }, + //created issue to solve that in ko https://github.com/SteveSanderson/knockout/issues/619 + isObservableArray: function (obj) { + return ko.isObservable(obj) && !(obj.destroyAll === undefined); } }; } ()); @@ -229,6 +234,14 @@ traverse(obj); + if (options.live) { + ko.utils.arrayForEach(validatables(), function (observable) { + if (utils.isObservableArray(observable)) { + observable.subscribe(function () { traverse(obj); }) + } + }); + } + result = ko.computed(function () { var errors = []; ko.utils.arrayForEach(validatables(), function (observable) { diff --git a/Tests/validation-tests.js b/Tests/validation-tests.js index b3bac4b3..0649cafc 100644 --- a/Tests/validation-tests.js +++ b/Tests/validation-tests.js @@ -902,7 +902,26 @@ test('Nested grouping finds items in observableArrays - observable', function () var errors = ko.validation.group(vm, { deep: true, observable: true }); equals(errors().length, 1, 'Grouping finds property on object in observableArray'); +}); + +test('Nested grouping does not add newly items newly inserted into observableArrays to result - observable, not live', function () { + var vm = { array: ko.observableArray() }; + + var errors = ko.validation.group(vm, { deep: true, observable: true, live: false }); + + vm.array.push( { one: ko.observable().extend( { required: true } ) }); + + equals(errors().length, 0, 'grouping does not add newly items newly inserted into observableArrays to result'); +}); + +test('Nested grouping adds items newly inserted into observableArrays to result - observable, live', function () { + var vm = { array: ko.observableArray() }; + + var errors = ko.validation.group(vm, { deep: true, observable: true, live: true }); + + vm.array.push( { one: ko.observable().extend( { required: true } ) }); + equals(errors().length, 1, 'grouping adds newly items newly inserted into observableArrays to result'); }); test('Issue #31 - Recursively Show All Messages', function () { From 7e7157ce85de3213ad80cc8900259b50b592ddb0 Mon Sep 17 00:00:00 2001 From: delixfe Date: Sat, 1 Sep 2012 17:36:33 +0200 Subject: [PATCH 003/165] grouping ignores items nested in destroyed objects (currently only working for non observable groupings) --- Src/knockout.validation.js | 3 ++- Tests/validation-tests.js | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/Src/knockout.validation.js b/Src/knockout.validation.js index cc56e3f1..32011bf5 100644 --- a/Src/knockout.validation.js +++ b/Src/knockout.validation.js @@ -214,7 +214,8 @@ } //get list of values either from array or object but ignore non-objects - if (val) { + // and destroyed objects + if (val && !val._destroy) { if (utils.isArray(val)) { objValues = val; } else if (utils.isObject(val)) { diff --git a/Tests/validation-tests.js b/Tests/validation-tests.js index 0649cafc..9544ff58 100644 --- a/Tests/validation-tests.js +++ b/Tests/validation-tests.js @@ -924,6 +924,31 @@ test('Nested grouping adds items newly inserted into observableArrays to result equals(errors().length, 1, 'grouping adds newly items newly inserted into observableArrays to result'); }); +test('Nested grouping ignores items nested in destroyed objects - not observable', function () { + var obj = { nested: ko.observable().extend({ required: true }) }; + + function getErrorCount() { + return errorsFn = ko.validation.group(obj, { deep: true, observable: false, live: false })().length; + } + + equal(getErrorCount(), 1, 'obj is not destroyed and should return nested\'s error'); + + obj._destroy = true; + + equal(getErrorCount(), 0, 'obj is destroyed and nested therefore ignored'); +}); + +test('Nested grouping ignores items nested in destroyed objects - observable, live', function () { + var obj = { nested: ko.observable().extend({ required: true }) }; + var array = ko.observableArray([obj]); + + var errors = ko.validation.group(array, { deep: true, observable: true, live: true }); + + equal(errors().length, 1, 'obj is not yet destroyed and nested therefore invalid'); + array.destroy(obj); + equal(errors().length, 0, 'obj is destroyed and nested therefore ignored'); +}); + test('Issue #31 - Recursively Show All Messages', function () { var vm = { one: ko.observable().extend({ required: true }), From ddab23b2fa9218ae578a8779fcd4c92d0f58886a Mon Sep 17 00:00:00 2001 From: delixfe Date: Sat, 1 Sep 2012 17:43:44 +0200 Subject: [PATCH 004/165] validateables were not cleared before retraversing the viewmodel --- Src/knockout.validation.js | 5 ++++- Tests/validation-tests.js | 11 +++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/Src/knockout.validation.js b/Src/knockout.validation.js index cc56e3f1..7c4db098 100644 --- a/Src/knockout.validation.js +++ b/Src/knockout.validation.js @@ -240,7 +240,10 @@ if (options.live) { ko.utils.arrayForEach(validatables(), function (observable) { if (utils.isObservableArray(observable)) { - observable.subscribe(function () { traverse(obj); }) + observable.subscribe(function () { + validatables([]); //clear validatables + traverse(obj); + }) } }); } diff --git a/Tests/validation-tests.js b/Tests/validation-tests.js index 0649cafc..25b03b2d 100644 --- a/Tests/validation-tests.js +++ b/Tests/validation-tests.js @@ -924,6 +924,17 @@ test('Nested grouping adds items newly inserted into observableArrays to result equals(errors().length, 1, 'grouping adds newly items newly inserted into observableArrays to result'); }); +test('Nested grouping adds items newly inserted into observableArrays to result - cleares validatables before traversing again - observable, live', function () { + var vm = { array: ko.observableArray() }; + + var errors = ko.validation.group(vm, { deep: true, observable: true, live: true }); + + vm.array.push({ one: ko.observable().extend({ required: true }) }); + vm.array.push({ one: ko.observable().extend({ required: true }) }); + + equals(errors().length, 2, 'validatables are added only once'); +}); + test('Issue #31 - Recursively Show All Messages', function () { var vm = { one: ko.observable().extend({ required: true }), From ae7b134c10d46f70061059cf624eeb96dbbcf024 Mon Sep 17 00:00:00 2001 From: delixfe Date: Thu, 22 Nov 2012 18:44:56 +0100 Subject: [PATCH 005/165] Added missing semicolon. --- Src/knockout.validation.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Src/knockout.validation.js b/Src/knockout.validation.js index e5b1f714..c9f92278 100644 --- a/Src/knockout.validation.js +++ b/Src/knockout.validation.js @@ -244,7 +244,7 @@ observable.subscribe(function () { validatables([]); //clear validatables traverse(obj); - }) + }); } }); } From ce20bd4166660ef4f2ba21cd2f2037271011678c Mon Sep 17 00:00:00 2001 From: delixfe Date: Fri, 23 Nov 2012 18:03:08 +0100 Subject: [PATCH 006/165] The traverse function of grouping stores the validatables in a temporary not observable array to avoid to cause the reevaluation of computeds depending on the errors for every added validatable. --- Src/knockout.validation.js | 14 +++++++++----- Tests/validation-tests.js | 21 +++++++++++++++++++-- 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/Src/knockout.validation.js b/Src/knockout.validation.js index c9f92278..a811596a 100644 --- a/Src/knockout.validation.js +++ b/Src/knockout.validation.js @@ -194,6 +194,7 @@ group: function group(obj, options) { // array of observables or viewModel var options = ko.utils.extend(configuration.grouping, options), validatables = ko.observableArray([]), + validatablesTemp = [], result = null, //anonymous, immediate function to traverse objects hierarchically @@ -210,7 +211,7 @@ //make sure it is validatable object if (!obj.isValid) obj.extend({ validatable: true }); - validatables.push(obj); + validatablesTemp.push(obj); } //get list of values either from array or object but ignore non-objects @@ -237,13 +238,16 @@ if (options.observable) { traverse(obj); + validatables(validatablesTemp); if (options.live) { ko.utils.arrayForEach(validatables(), function (observable) { if (utils.isObservableArray(observable)) { observable.subscribe(function () { - validatables([]); //clear validatables + validatablesTemp = []; + //validatables([]); //clear validatables traverse(obj); + validatables(validatablesTemp); }); } }); @@ -262,9 +266,9 @@ } else { //if not using observables then every call to error() should traverse the structure result = function () { var errors = []; - validatables([]); //clear validatables + validatablesTemp = []; //clear validatables traverse(obj); // and traverse tree again - ko.utils.arrayForEach(validatables(), function (observable) { + ko.utils.arrayForEach(validatablesTemp, function (observable) { if (!observable.isValid()) { errors.push(observable.error); } @@ -282,7 +286,7 @@ // ensure we have latest changes result(); - ko.utils.arrayForEach(validatables(), function (observable) { + ko.utils.arrayForEach(validatablesTemp, function (observable) { observable.isModified(show); }); }; diff --git a/Tests/validation-tests.js b/Tests/validation-tests.js index d0088955..99efbc7c 100644 --- a/Tests/validation-tests.js +++ b/Tests/validation-tests.js @@ -904,7 +904,7 @@ test('Nested grouping finds items in observableArrays - observable', function () equals(errors().length, 1, 'Grouping finds property on object in observableArray'); }); -test('Nested grouping does not add newly items newly inserted into observableArrays to result - observable, not live', function () { +test('Nested grouping does not add items newly inserted into observableArrays to result - observable, not live', function () { var vm = { array: ko.observableArray() }; var errors = ko.validation.group(vm, { deep: true, observable: true, live: false }); @@ -941,14 +941,31 @@ test('Nested grouping ignores items nested in destroyed objects - not observable test('Nested grouping ignores items nested in destroyed objects - observable, live', function () { var obj = { nested: ko.observable().extend({ required: true }) }; var array = ko.observableArray([obj]); + var vm = { array: array}; - var errors = ko.validation.group(array, { deep: true, observable: true, live: true }); + var errors = ko.validation.group(vm, { deep: true, observable: true, live: true }); equal(errors().length, 1, 'obj is not yet destroyed and nested therefore invalid'); array.destroy(obj); equal(errors().length, 0, 'obj is destroyed and nested therefore ignored'); }); +test('Nested grouping does not cause the reevaluation of computeds depending on the result for every observable', function () { + var vm = { array: ko.observableArray() }; + var item = { one: ko.observable().extend( { required: true } ) }; + + var errors = ko.validation.group(vm, { deep: true, observable: true, live: true }); + + var computedHitCount = 0; + var computed = ko.computed(function () { + computedHitCount++; + errors(); + }); + + vm.array.push(item); + equals(computedHitCount, 2, ' first on while creating the computed, second one for adding the item'); +}); + test('Nested grouping adds items newly inserted into observableArrays to result - cleares validatables before traversing again - observable, live', function () { var vm = { array: ko.observableArray() }; From 6f79d9fb3a3ea203ade8a9e27b09440006f21f10 Mon Sep 17 00:00:00 2001 From: delixfe Date: Fri, 23 Nov 2012 18:05:08 +0100 Subject: [PATCH 007/165] Removed a comment. --- Src/knockout.validation.js | 1 - 1 file changed, 1 deletion(-) diff --git a/Src/knockout.validation.js b/Src/knockout.validation.js index a811596a..0cdf9d76 100644 --- a/Src/knockout.validation.js +++ b/Src/knockout.validation.js @@ -245,7 +245,6 @@ if (utils.isObservableArray(observable)) { observable.subscribe(function () { validatablesTemp = []; - //validatables([]); //clear validatables traverse(obj); validatables(validatablesTemp); }); From 4888a1c2ababadd5675d1903c94b3d2d406bc94d Mon Sep 17 00:00:00 2001 From: delixfe Date: Sun, 23 Dec 2012 17:25:46 +0100 Subject: [PATCH 008/165] Use validatablesTemp instead of the call to validatables() to subscribe to all observableArrays. --- Src/knockout.validation.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Src/knockout.validation.js b/Src/knockout.validation.js index 4ef8ce3b..109284f6 100644 --- a/Src/knockout.validation.js +++ b/Src/knockout.validation.js @@ -253,7 +253,7 @@ validatables(validatablesTemp); if (options.live) { - ko.utils.arrayForEach(validatables(), function (observable) { + ko.utils.arrayForEach(validatablesTemp, function (observable) { if (utils.isObservableArray(observable)) { observable.subscribe(function () { validatablesTemp = []; From 44bf5c256f33b395ec5dfac5ccaaa37c3bcacb3f Mon Sep 17 00:00:00 2001 From: delixfe Date: Sun, 23 Dec 2012 17:49:08 +0100 Subject: [PATCH 009/165] Live tracking of observableArrays did work only on the arrays existing at the creation of the validation group. --- Src/knockout.validation.js | 38 +++++++++++++++++++++++--------------- Tests/validation-tests.js | 11 +++++++++++ 2 files changed, 34 insertions(+), 15 deletions(-) diff --git a/Src/knockout.validation.js b/Src/knockout.validation.js index 109284f6..185da545 100644 --- a/Src/knockout.validation.js +++ b/Src/knockout.validation.js @@ -224,6 +224,10 @@ //make sure it is validatable object if (!obj.isValid) obj.extend({ validatable: true }); validatablesTemp.push(obj); + + if(options.live && utils.isObservableArray(obj)) { + subscribeToObservableArray(obj); + } } //get list of values either from array or object but ignore non-objects @@ -244,26 +248,30 @@ if (observable && !observable.nodeType) traverse(observable, level + 1); }); } + }, + + observableArraySubscriptions = [], + clearObservableArraySubscriptions = function () { + ko.utils.arrayForEach(observableArraySubscriptions, function (subscription) { + subscription.dispose(); + }); + observableArraySubscriptions = []; + }, + traverseAndStoreInValidatables = function() { + clearObservableArraySubscriptions(); + validatablesTemp = []; + traverse(obj); + validatables(validatablesTemp); + }, + subscribeToObservableArray = function(observableArray) { + observableArraySubscriptions.push(observableArray.subscribe(traverseAndStoreInValidatables)); }; //if using observables then traverse structure once and add observables if (options.observable) { - traverse(obj); - validatables(validatablesTemp); - - if (options.live) { - ko.utils.arrayForEach(validatablesTemp, function (observable) { - if (utils.isObservableArray(observable)) { - observable.subscribe(function () { - validatablesTemp = []; - traverse(obj); - validatables(validatablesTemp); - }); - } - }); - } - + traverseAndStoreInValidatables(); + result = ko.computed(function () { var errors = []; ko.utils.arrayForEach(validatables(), function (observable) { diff --git a/Tests/validation-tests.js b/Tests/validation-tests.js index 9306dc4b..b0fc9ef1 100644 --- a/Tests/validation-tests.js +++ b/Tests/validation-tests.js @@ -964,6 +964,17 @@ test('Nested grouping does not add items newly inserted into observableArrays to equals(errors().length, 0, 'grouping does not add newly items newly inserted into observableArrays to result'); }); +test('Nested grouping adds items newly inserted into an observableArrays nested in an object in an observableArray to result - observable, live', function () { + var vm = { array: ko.observableArray() }; + + var errors = ko.validation.group(vm, { deep: true, observable: true, live: true }); + + vm.array.push({ array: ko.observableArray() }); + vm.array()[0].array.push( { one: ko.observable().extend( { required: true } ) }); + + equals(errors().length, 1, 'grouping adds newly items newly inserted into observableArrays to result'); +}); + test('Nested grouping adds items newly inserted into observableArrays to result - observable, live', function () { var vm = { array: ko.observableArray() }; From 372b09cc626e2a5da535943e01171b64f874d655 Mon Sep 17 00:00:00 2001 From: delixfe Date: Sun, 23 Dec 2012 18:10:26 +0100 Subject: [PATCH 010/165] Added a todo for dispose handling. --- Src/knockout.validation.js | 1 + 1 file changed, 1 insertion(+) diff --git a/Src/knockout.validation.js b/Src/knockout.validation.js index 185da545..2a8a97ed 100644 --- a/Src/knockout.validation.js +++ b/Src/knockout.validation.js @@ -272,6 +272,7 @@ traverseAndStoreInValidatables(); + // TODO: call clearObservableArraySubscriptions on dispose of result -> but ko.computed has no disposeCallback result = ko.computed(function () { var errors = []; ko.utils.arrayForEach(validatables(), function (observable) { From b91e535a9887f4e7708b337d3ac6d1f7ed10e9e6 Mon Sep 17 00:00:00 2001 From: dgaviola Date: Fri, 1 Mar 2013 14:47:25 -0300 Subject: [PATCH 011/165] Number validator. Allow numbers starting with point. --- Src/knockout.validation.js | 2 +- Tests/validation-tests.js | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/Src/knockout.validation.js b/Src/knockout.validation.js index cf4dd6e2..49e3735f 100644 --- a/Src/knockout.validation.js +++ b/Src/knockout.validation.js @@ -490,7 +490,7 @@ ko.validation.rules['number'] = { validator: function (value, validate) { - return utils.isEmptyVal(value) || (validate && /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value)); + return utils.isEmptyVal(value) || (validate && /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(value)); }, message: 'Please enter a number' }; diff --git a/Tests/validation-tests.js b/Tests/validation-tests.js index e80fadd1..2356483d 100644 --- a/Tests/validation-tests.js +++ b/Tests/validation-tests.js @@ -387,6 +387,15 @@ test('Object is Valid and isValid returns True', function () { ok(testObj.isValid(), 'testObj is Valid'); }); +test('Number is Valid (starting with point) and isValid returns True', function () { + var testObj = ko.observable('').extend({ number: true }); + + testObj(".15"); + + equal(testObj(), ".15", 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + test('Object is NOT Valid and isValid returns False', function () { var testObj = ko.observable('').extend({ number: true }); From 1f0e498d6548660895c695d009dc7f67ba22a1ac Mon Sep 17 00:00:00 2001 From: Eric Barnard Date: Tue, 16 Apr 2013 13:06:36 -0500 Subject: [PATCH 012/165] Update and rename ReadMe.md to README.md - added Steve to the contributors list since he's a new co-maintainer --- ReadMe.md => README.md | 1 + 1 file changed, 1 insertion(+) rename ReadMe.md => README.md (98%) diff --git a/ReadMe.md b/README.md similarity index 98% rename from ReadMe.md rename to README.md index 2c60cc8b..7e4c8c2c 100644 --- a/ReadMe.md +++ b/README.md @@ -4,6 +4,7 @@ A KnockoutJS Plugin for model and property validation Contributors: * [Eric Barnard](https://github.com/ericmbarnard) +* [Steve Greatrex](https://github.com/stevegreatrex) * [Andy Booth](https://github.com/andybooth) * [Michal Poreba](https://github.com/michalporeba) * and many others! From 2b3cf17c35d9b8d2216dff5e0be952ac620d70ec Mon Sep 17 00:00:00 2001 From: Eric Barnard Date: Thu, 18 Apr 2013 09:19:15 -0500 Subject: [PATCH 013/165] Updated Links to point to new GitHub Repo/Wiki --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 7e4c8c2c..0fd23f40 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,7 @@ var myObj = ko.observable('').extend({ maxLength: 12 }); var myObj = ko.observable('').extend({ email: true }); ``` -... and [MANY MORE](https://github.com/ericmbarnard/Knockout-Validation/wiki/Native-Rules) +... and [MANY MORE](https://github.com/Knockout-Contrib/Knockout-Validation/wiki/Native-Rules) _Much thanks to the [jQuery Validation Plug-In](https://github.com/jzaefferer/jquery-validation) team for their work on many of the rules_ ##Custom Validation Rules @@ -107,9 +107,9 @@ ko.validation.registerExtenders(); //the value '5' is the second arg ('otherVal') that is passed to the validator var myCustomObj = ko.observable().extend({ mustEqual: 5 }); ``` -Learn more about Custom Rules on the [WIKI](https://github.com/ericmbarnard/Knockout-Validation/wiki/Custom-Validation-Rules) +Learn more about Custom Rules on the [WIKI](https://github.com/Knockout-Contrib/Knockout-Validation/wiki/Custom-Validation-Rules) -###Or Check out our [User-Contributed Custom Rules](https://github.com/ericmbarnard/Knockout-Validation/wiki/User-Contributed-Rules)!### +###Or Check out our [User-Contributed Custom Rules](https://github.com/Knockout-Contrib/Knockout-Validation/wiki/User-Contributed-Rules)!### ##HTML5 Validation Attributes @@ -136,10 +136,10 @@ If you want to customize the display of your objects validation message, use the

``` -Check out more on [Validation Bindings](https://github.com/ericmbarnard/Knockout-Validation/wiki/Validation-Bindings) +Check out more on [Validation Bindings](https://github.com/Knockout-Contrib/Knockout-Validation/wiki/Validation-Bindings) ##Remote Validation Rules -Check out our [Async Validation](https://github.com/ericmbarnard/Knockout-Validation/wiki/Async-Rules) and [jQuery AJAX Validation](https://github.com/ericmbarnard/Knockout-Validation/wiki/Async-Rules) +Check out our [Async Validation](https://github.com/Knockout-Contrib/Knockout-Validation/wiki/Async-Rules) and [jQuery AJAX Validation](https://github.com/ericmbarnard/Knockout-Validation/wiki/Async-Rules) ##Localization From 794f199356591c7a78351a303844fdb409eb328a Mon Sep 17 00:00:00 2001 From: yiqing-95 Date: Sat, 20 Apr 2013 10:36:04 +0800 Subject: [PATCH 014/165] add the chinese localization file --- Localization/el-GR.js | 76 +++++++++++++++++++++---------------------- Localization/zh-CN.js | 39 ++++++++++++++++++++++ 2 files changed, 77 insertions(+), 38 deletions(-) create mode 100644 Localization/zh-CN.js diff --git a/Localization/el-GR.js b/Localization/el-GR.js index f756ae85..a277d033 100644 --- a/Localization/el-GR.js +++ b/Localization/el-GR.js @@ -1,39 +1,39 @@ -/// - -/************************************************ -* This is an example localization page. All of these -* messages are the default messages for ko.validation -* -* Currently ko.validation only does a single parameter replacement -* on your message (indicated by the {0}). -* -* The parameter that you provide in your validation extender -* is what is passed to your message to do the {0} replacement. -* -* eg: myProperty.extend({ minLength: 5 }); -* ... will provide a message of "Please enter at least 5 characters" -* when validated -* -* This message replacement obviously only works with primitives -* such as numbers and strings. We do not stringify complex objects -* or anything like that currently. -*/ - -ko.validation.localize({ - required: 'Το πεδίο αυτό είναι υποχρεωτικό.', - min: 'Παρακαλώ εισάγετε μια τιμή μεγαλύτερη ή ίση από {0}.', - max: 'Παρακαλώ εισάγετε μια τιμή μικρότερη ή ίση από {0}.', - minLength: 'Παρακαλώ εισάγετε τουλάχιστον {0} χαρακτήρες.', - maxLength: 'Παρακαλώ εισάγετε το πολύ {0} χαρακτήρες.', - pattern: 'Παρακαλώ ελέγξτε την τιμή αυτή.', - step: 'Η τιμή πρέπει να αυξηθεί κατά {0}', - email: 'Η διεύθυνση email δεν έχει έγκυρη μορφή', - date: 'Παρακαλώ εισάγετε μια έγκυρη ημερομηνία', - dateISO: 'Παρακαλώ εισάγετε μια έγκυρη ημερομηνία', - number: 'Παρακαλώ εισάγετε έναν αριθμό', - digit: 'Παρακαλώ εισάγετε ένα ψηφίο', - phoneUS: 'Παρακαλώ εισάγετε έναν σωστό αριθμό τηλεφώνου', - equal: 'Οι τιμές πρέπει να είναι ίσες', - notEqual: 'Παρακαλώ επιλέξτε μια άλλη τιμή.', - unique: 'Παρακαλώ βεβαιωθείτε ότι η τιμή είναι μοναδική.' +/// + +/************************************************ +* This is an example localization page. All of these +* messages are the default messages for ko.validation +* +* Currently ko.validation only does a single parameter replacement +* on your message (indicated by the {0}). +* +* The parameter that you provide in your validation extender +* is what is passed to your message to do the {0} replacement. +* +* eg: myProperty.extend({ minLength: 5 }); +* ... will provide a message of "Please enter at least 5 characters" +* when validated +* +* This message replacement obviously only works with primitives +* such as numbers and strings. We do not stringify complex objects +* or anything like that currently. +*/ + +ko.validation.localize({ + required: 'Το πεδίο αυτό είναι υποχρεωτικό.', + min: 'Παρακαλώ εισάγετε μια τιμή μεγαλύτερη ή ίση από {0}.', + max: 'Παρακαλώ εισάγετε μια τιμή μικρότερη ή ίση από {0}.', + minLength: 'Παρακαλώ εισάγετε τουλάχιστον {0} χαρακτήρες.', + maxLength: 'Παρακαλώ εισάγετε το πολύ {0} χαρακτήρες.', + pattern: 'Παρακαλώ ελέγξτε την τιμή αυτή.', + step: 'Η τιμή πρέπει να αυξηθεί κατά {0}', + email: 'Η διεύθυνση email δεν έχει έγκυρη μορφή', + date: 'Παρακαλώ εισάγετε μια έγκυρη ημερομηνία', + dateISO: 'Παρακαλώ εισάγετε μια έγκυρη ημερομηνία', + number: 'Παρακαλώ εισάγετε έναν αριθμό', + digit: 'Παρακαλώ εισάγετε ένα ψηφίο', + phoneUS: 'Παρακαλώ εισάγετε έναν σωστό αριθμό τηλεφώνου', + equal: 'Οι τιμές πρέπει να είναι ίσες', + notEqual: 'Παρακαλώ επιλέξτε μια άλλη τιμή.', + unique: 'Παρακαλώ βεβαιωθείτε ότι η τιμή είναι μοναδική.' }); \ No newline at end of file diff --git a/Localization/zh-CN.js b/Localization/zh-CN.js new file mode 100644 index 00000000..9e86ffd8 --- /dev/null +++ b/Localization/zh-CN.js @@ -0,0 +1,39 @@ +/// + +/************************************************ + * This is an example localization page All of these + * messages are the default messages for kovalidation + * + * Currently kovalidation only does a single parameter replacement + * on your message (indicated by the {0}) + * + * The parameter that you provide in your validation extender + * is what is passed to your message to do the {0} replacement + * + * eg: myPropertyextend({ minLength: 5 }); + * will provide a message of "Please enter at least 5 characters" + * when validated + * + * This message replacement obviously only works with primitives + * such as numbers and strings We do not stringify complex objects + * or anything like that currently + */ + +ko.validation.localize({ + required: '必填字段', + min: '输入值必须大于等于 {0}', + max: '输入值必须小于等于 {0}', + minLength: '至少输入 {0} 个字符', + maxLength: '输入的字符数不能超过 {0} 个', + pattern: '请检查此值', + step: '每次步进值是 {0}', + email: 'email地址格式不正确', + date: '日期格式不正确', + dateISO: '日期格式不正确', + number: '请输入一个数字', + digit: '请输入一个数字', + phoneUS: '请输入一个合法的手机号(US)', + equal: '输入值不一样', + notEqual: '请选择另一个值', + unique: '此值应该是唯一的' +}); \ No newline at end of file From 42e69aecbaecc5b2815beff75603d8761269a2a3 Mon Sep 17 00:00:00 2001 From: yiqing-95 Date: Sat, 20 Apr 2013 10:42:30 +0800 Subject: [PATCH 015/165] accidently do a minor modification to the el-GR.js file --- Localization/el-GR.js | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/Localization/el-GR.js b/Localization/el-GR.js index a277d033..32128ba0 100644 --- a/Localization/el-GR.js +++ b/Localization/el-GR.js @@ -1,23 +1,23 @@ /// /************************************************ -* This is an example localization page. All of these -* messages are the default messages for ko.validation -* -* Currently ko.validation only does a single parameter replacement -* on your message (indicated by the {0}). -* -* The parameter that you provide in your validation extender -* is what is passed to your message to do the {0} replacement. -* -* eg: myProperty.extend({ minLength: 5 }); -* ... will provide a message of "Please enter at least 5 characters" -* when validated -* -* This message replacement obviously only works with primitives -* such as numbers and strings. We do not stringify complex objects -* or anything like that currently. -*/ + * This is an example localization page. All of these + * messages are the default messages for ko.validation + * + * Currently ko.validation only does a single parameter replacement + * on your message (indicated by the {0}). + * + * The parameter that you provide in your validation extender + * is what is passed to your message to do the {0} replacement. + * + * eg: myProperty.extend({ minLength: 5 }); + * ... will provide a message of "Please enter at least 5 characters" + * when validated + * + * This message replacement obviously only works with primitives + * such as numbers and strings. We do not stringify complex objects + * or anything like that currently. + */ ko.validation.localize({ required: 'Το πεδίο αυτό είναι υποχρεωτικό.', From 030aee06d8d15d0b6db6ff25b2cd00e36259af00 Mon Sep 17 00:00:00 2001 From: Edimar Lima Date: Fri, 3 May 2013 10:56:42 -0300 Subject: [PATCH 016/165] pt-BR localization messages enhancements and typo fixes --- Localization/pt-BR.js | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/Localization/pt-BR.js b/Localization/pt-BR.js index 6da004e8..ddb9f859 100644 --- a/Localization/pt-BR.js +++ b/Localization/pt-BR.js @@ -20,20 +20,20 @@ */ ko.validation.localize({ - required: 'Este campo é requerido.', - min: 'Por favor, forneça um valor maior ou igual a {0}.', - max: 'Por favor, forneça um valor menor ou igual a {0}.', - minLength: 'Por favor, forneça ao menos {0} caracteres.', - maxLength: 'Por favor, forneça não mais que {0} caracteres.', + required: 'Este campo é obrigatório.', + min: 'Por favor, informe um valor maior ou igual a {0}.', + max: 'Por favor, informe um valor menor ou igual a {0}.', + minLength: 'Por favor, informe ao menos {0} caracteres.', + maxLength: 'Por favor, informe no máximo {0} caracteres.', pattern: 'Por favor, verifique este valor', step: 'O valor deve ser incrementado por {0}', - email: 'Por favor, forneça um endereço eletrônico válido.', - date: 'Por favor, forneça uma data válida.', - dateISO: 'Por favor, forneça uma data válida (ISO).', - number: 'Por favor, forneça um número válido.', - digit: 'Por favor, forneça somente dígitos.', - phoneUS: 'Por favor, forneça um telefone válido', + email: 'Por favor, informe um e-mail válido.', + date: 'Por favor, informe uma data válida.', + dateISO: 'Por favor, informe uma data válida (ISO).', + number: 'Por favor, informe um número válido.', + digit: 'Por favor, utilize somente dígitos.', + phoneUS: 'Por favor, informe um telefone válido', equal: 'Os valores devem ser iguais', - notEqual: 'Por faovr, escolha outro valor', + notEqual: 'Por favor, informe outro valor', unique: 'Verifique se o valor é único' -}); \ No newline at end of file +}); From c71e75aac2cd4167eb2b4284284c715f6a5742f7 Mon Sep 17 00:00:00 2001 From: James Dunlop Date: Sat, 25 May 2013 10:39:59 +1000 Subject: [PATCH 017/165] Reorder phoneUS extender validation checks Reorder phoneUS validation checks to preserve optional properties if observable is not initialized or null. Add unit tests to other extenders to reflect optional properties for uninitialized or null condition. --- Src/knockout.validation.js | 2 +- Tests/validation-tests.js | 207 +++++++++++++++++++++++++++++++++---- 2 files changed, 188 insertions(+), 21 deletions(-) diff --git a/Src/knockout.validation.js b/Src/knockout.validation.js index 009da6ea..ef49191e 100644 --- a/Src/knockout.validation.js +++ b/Src/knockout.validation.js @@ -664,8 +664,8 @@ validation.rules['phoneUS'] = { validator: function (phoneNumber, validate) { if (!validate) { return true; } - if (typeof (phoneNumber) !== 'string') { return false; } if (utils.isEmptyVal(phoneNumber)) { return true; } // makes it optional, use 'required' rule if it should be required + if (typeof (phoneNumber) !== 'string') { return false; } phoneNumber = phoneNumber.replace(/\s+/g, ""); return validate && phoneNumber.length > 9 && phoneNumber.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/); }, diff --git a/Tests/validation-tests.js b/Tests/validation-tests.js index 039124c2..420c6b68 100644 --- a/Tests/validation-tests.js +++ b/Tests/validation-tests.js @@ -64,7 +64,21 @@ test('Issue #90 - "required: false" doesnt force validation', function () { module('Min Validation'); -test('Object is Valid when no value is present - Preserves Optional Properties', function () { +test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ min: 2 }); + testObj(); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when null value is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ min: 2 }); + testObj(null); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when empty string is present - Preserves Optional Properties', function () { var testObj = ko.observable().extend({ min: 2 }); testObj(''); @@ -105,13 +119,27 @@ test('Object is NOT Valid and isValid returns False', function () { //#region Max Validation module('Max Validation'); -test('Object is Valid when no value is present - Preserves Optional Properties', function () { + +test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { var testObj = ko.observable().extend({ max: 2 }); - testObj(''); + testObj(); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when null value is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ max: 2 }); + testObj(null); ok(testObj.isValid(), 'testObj is Valid'); }); +test('Object is Valid when empty string is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ max: 2 }); + testObj(''); + ok(testObj.isValid(), 'testObj is Valid'); +}); test('Object is Valid and isValid returns True', function () { var testObj = ko.observable('') @@ -139,6 +167,27 @@ test('Object is NOT Valid and isValid returns False', function () { module('MinLength Validation'); +test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ minLength: 2 }); + testObj(); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when null value is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ minLength: 2 }); + testObj(null); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when empty string is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ minLength: 2 }); + testObj(''); + ok(testObj.isValid(), 'testObj is Valid'); +}); + test('Object is Valid when no value is present - Preserves Optional Properties', function () { var testObj = ko.observable().extend({ minLength: 2 }); @@ -188,7 +237,21 @@ test('Issue #33 - Arrays - Invalid', function () { module('MaxLength Validation'); -test('Object is Valid when no value is present - Preserves Optional Properties', function () { +test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ maxLength: 2 }); + testObj(); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when null value is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ maxLength: 2 }); + testObj(null); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when empty string is present - Preserves Optional Properties', function () { var testObj = ko.observable().extend({ maxLength: 2 }); testObj(''); @@ -236,7 +299,21 @@ test('Issue #33 - Arrays - Invalid', function () { module('Pattern Validation'); -test('Object is Valid when no value is present - Preserves Optional Properties', function () { +test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ pattern: 'test' }); + testObj(); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when null value is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ pattern: 'test' }); + testObj(null); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when empty string is present - Preserves Optional Properties', function () { var testObj = ko.observable().extend({ pattern: 'test' }); testObj(''); @@ -287,13 +364,6 @@ test('Pattern validation doesn\'t break with non-string values', function () { var testObj = ko.observable('') .extend({ pattern: '^$' }); - // Validation results not important, just shouldn't blow-up - testObj(null); - testObj.isValid(); - - testObj(undefined); - testObj.isValid(); - testObj(12345); testObj.isValid(); @@ -319,7 +389,21 @@ test('Pattern validation doesn\'t break with non-string values', function () { module('Step Validation'); -test('Object is Valid when no value is present - Preserves Optional Properties', function () { +test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ step: 2 }); + testObj(); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when null value is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ step: 2 }); + testObj(null); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when empty string is present - Preserves Optional Properties', function () { var testObj = ko.observable().extend({ step: 2 }); testObj(''); @@ -383,7 +467,21 @@ test('Issue 74 - Object is NOT Valid with a step of 0.1 and isValid returns Fals module('Email Validation'); -test('Object is Valid when no value is present - Preserves Optional Properties', function () { +test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ email: true }); + testObj(); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when null value is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ email: true }); + testObj(null); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when empty string is present - Preserves Optional Properties', function () { var testObj = ko.observable().extend({ email: true }); testObj(''); @@ -423,7 +521,21 @@ test('Email with invalid domain', function(){ module('Date Validation'); -test('Object is Valid when no value is present - Preserves Optional Properties', function () { +test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ date: 'test' }); + testObj(); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when null value is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ date: 'test' }); + testObj(null); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when empty string is present - Preserves Optional Properties', function () { var testObj = ko.observable().extend({ date: 'test' }); testObj(''); @@ -454,7 +566,21 @@ test('Object is NOT Valid and isValid returns False', function () { module('DateISO Validation'); -test('Object is Valid when no value is present - Preserves Optional Properties', function () { +test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ dateISO: 'test' }); + testObj(); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when null value is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ dateISO: 'test' }); + testObj(null); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when empty string is present - Preserves Optional Properties', function () { var testObj = ko.observable().extend({ dateISO: 'test' }); testObj(''); @@ -485,7 +611,21 @@ test('Object is NOT Valid and isValid returns False', function () { module('Number Validation'); -test('Object is Valid when no value is present - Preserves Optional Properties', function () { +test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ number: true }); + testObj(); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when null value is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ number: true }); + testObj(null); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when empty string is present - Preserves Optional Properties', function () { var testObj = ko.observable().extend({ number: true }); testObj(''); @@ -516,7 +656,21 @@ test('Object is NOT Valid and isValid returns False', function () { module('Digit Validation'); -test('Object is Valid when no value is present - Preserves Optional Properties', function () { +test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ digit: true }); + testObj(); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when null value is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ digit: true }); + testObj(null); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when empty string is present - Preserves Optional Properties', function () { var testObj = ko.observable().extend({ digit: true }); testObj(''); @@ -546,13 +700,26 @@ test('Object is NOT Valid and isValid returns False', function () { //#region PhoneUS Validation module('PhoneUS Validation'); -test('Object is Valid when no value is present - Preserves Optional Properties', function () { +test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { var testObj = ko.observable().extend({ phoneUS: true }); - testObj(''); + testObj(); ok(testObj.isValid(), 'testObj is Valid'); }); +test('Object is Valid when null value is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ phoneUS: true }); + testObj(null); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when empty string is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ phoneUS: true }); + testObj(''); + ok(testObj.isValid(), 'testObj is Valid'); +}); test('Object is Valid and isValid returns True', function () { var testObj = ko.observable('').extend({ phoneUS: true }); From f8f9cca6580f15d9e29c4eacef830d39759c25e8 Mon Sep 17 00:00:00 2001 From: Steve Greatrex Date: Wed, 29 May 2013 20:42:20 +0100 Subject: [PATCH 018/165] Invoked error as an observable instead of setting it directly --- Src/knockout.validation.js | 4 ++-- Tests/validation-tests.js | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Src/knockout.validation.js b/Src/knockout.validation.js index 009da6ea..3bea0fd0 100644 --- a/Src/knockout.validation.js +++ b/Src/knockout.validation.js @@ -949,13 +949,13 @@ //manually set error state observable.setError = function (error) { - observable.error = error; + observable.error(error); observable.__valid__(false); }; //manually clear error state observable.clearError = function () { - observable.error = null; + observable.error(null); observable.__valid__(true); } diff --git a/Tests/validation-tests.js b/Tests/validation-tests.js index 039124c2..1c859736 100644 --- a/Tests/validation-tests.js +++ b/Tests/validation-tests.js @@ -829,14 +829,14 @@ test("setError sets isValid and error message", function () { //check initial validation state ok(testObj.isValid()); - equal(testObj.error, null); + equal(testObj.error(), null); //manually set an error testObj.setError("oh no!"); //check state was set ok(!testObj.isValid()); - equal("oh no!", testObj.error); + equal("oh no!", testObj.error()); }); test("clearError clears manually-specified error", function () { @@ -852,7 +852,7 @@ test("clearError clears manually-specified error", function () { //check state was cleared ok(testObj.isValid()); - equal(testObj.error, null); + equal(testObj.error(), null); }); test("clearError clears automatic errors", function () { @@ -866,7 +866,7 @@ test("clearError clears automatic errors", function () { //check validation was cleared ok(testObj.isValid()); - equal(testObj.error, null); + equal(testObj.error(), null); }); //#endregion From a34b84c7f51d82cd01920ba6384f3bce242a28b4 Mon Sep 17 00:00:00 2001 From: Ingvar Stepanyan Date: Wed, 19 Jun 2013 17:52:43 +0300 Subject: [PATCH 019/165] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0fd23f40..8d9dd82d 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ myViewModel().property2(9); console.log(myViewModel.isValid()); //true ``` -see more examples on the Fiddle: http://jsfiddle.net/ericbarnard/KHFn8/ +see more examples on the Fiddle: http://jsfiddle.net/KHFn8/2971/ ##Native Validation Rules **Required**: From e102b7f6307912f8c9470fffbf0c2b1cd9dfae8b Mon Sep 17 00:00:00 2001 From: Alex Paven Date: Mon, 24 Jun 2013 12:07:50 +0100 Subject: [PATCH 020/165] Step validation fix with tests Step validation fails for valid changes under certain conditions, due to floating point rounding errors. For instance, 33.34 * 100 will yield a value very close to 3334, but slightly above it and will never equal 3334 exactly. This somewhat fixes this by making less strict checks (modulus should be within a certain tolerance of zero, and the tolerance could be increased if for some crazy reason someone wanted more precision). This also allows the step parameter to have the 'any' value, which is valid according to the HTML5 spec. --- Src/knockout.validation.js | 4 +++- Tests/validation-tests.js | 11 +++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/Src/knockout.validation.js b/Src/knockout.validation.js index 3bea0fd0..4cb77bc4 100644 --- a/Src/knockout.validation.js +++ b/Src/knockout.validation.js @@ -610,7 +610,9 @@ // 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 - return utils.isEmptyVal(val) || (val * 100) % (step * 100) === 0; + if (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; }, message: 'The value must increment by {0}' }; diff --git a/Tests/validation-tests.js b/Tests/validation-tests.js index 1c859736..b2126b31 100644 --- a/Tests/validation-tests.js +++ b/Tests/validation-tests.js @@ -377,6 +377,17 @@ test('Issue 74 - Object is NOT Valid with a step of 0.1 and isValid returns Fals equal(testObj(), 5.15, 'observable still works'); equal(testObj.isValid(), false, 'testObj is not valid'); }); + +test('Step validation fix regression check', function() { + var testObj = ko.observable(33.34).extend({ step: 0.01}); + ok(!testObj.error(), 'step validation not triggered'); +}); + +test('Step validation any value is allowed', function() { + var testObj = ko.observable(33.34).extend({ step: 'any' }); + ok(!testObj.error(), '"any" value for step is allowed'); +}); + //#endregion //#region Email Validation From c168b75b58600d63207d12db675ac96e341bad16 Mon Sep 17 00:00:00 2001 From: AndersMalmgren Date: Fri, 23 Aug 2013 12:52:25 +0200 Subject: [PATCH 021/165] Fix for Issue #313 Grouping should be able to traverse object structures that has cyclic references --- Src/knockout.validation.js | 25 ++++++++++++++++++++----- Tests/validation-tests.js | 12 ++++++++++++ 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/Src/knockout.validation.js b/Src/knockout.validation.js index 4cb77bc4..99cc80ef 100644 --- a/Src/knockout.validation.js +++ b/Src/knockout.validation.js @@ -233,13 +233,28 @@ var validatables = ko.observableArray([]), result = null, + flagged = [], + dispose = function () { + if (options.deep) { + ko.utils.arrayForEach(flagged, function (obj) { + delete obj.__kv_traversed; + }); + } + }, //anonymous, immediate function to traverse objects hierarchically //if !options.deep then it will stop on top level traverse = function traverse(obj, level) { var objValues = [], val = ko.utils.unwrapObservable(obj); + if (obj.__kv_traversed === true) return; + + if (options.deep) { + obj.__kv_traversed = true; + flagged.push(obj); + } + //default level value depends on deep option. level = (level !== undefined ? level : options.deep ? 1 : -1); @@ -274,6 +289,7 @@ if (options.observable) { traverse(obj); + dispose(); result = ko.computed(function () { var errors = []; @@ -290,6 +306,7 @@ var errors = []; validatables([]); //clear validatables traverse(obj); // and traverse tree again + dispose(); ko.utils.arrayForEach(validatables(), function (observable) { if (!observable.isValid()) { errors.push(observable.error); @@ -297,8 +314,6 @@ }); return errors; }; - - } result.showAllMessages = function (show) { // thanks @heliosPortal @@ -318,12 +333,12 @@ obj.isValid = function () { return obj.errors().length === 0; }; - obj.isAnyMessageShown = function() { + obj.isAnyMessageShown = function () { var invalidAndModifiedPresent = false; - + // ensure we have latest changes result(); - + ko.utils.arrayForEach(validatables(), function (observable) { if (!observable.isValid() && observable.isModified()) { invalidAndModifiedPresent = true; diff --git a/Tests/validation-tests.js b/Tests/validation-tests.js index b2126b31..9529992b 100644 --- a/Tests/validation-tests.js +++ b/Tests/validation-tests.js @@ -1130,6 +1130,18 @@ test("Issue #235 - formatMessage should unwrap observable parameters", function formatted = ko.validation.formatMessage(format, "a value"); equal("Format message: a value", formatted, "Message should be formatted with the non-observable value"); }); + +test("Issue #313 - When recursivly iterating object tree with deep option", function() { + var vm = function() { + this.required = ko.observable().extend({ required: true}); + this.child = this; + }; + + var errors = ko.validation.group(new vm(), { observable: true, deep: true}); + + ok(true, "It should not throw stack overflow"); + equal(errors().length, 1); +}); //#endregion //#region Conditional Validation From 4628951f955f6a733c4ae619514914d517da2ee4 Mon Sep 17 00:00:00 2001 From: Nick Young Date: Mon, 2 Sep 2013 15:01:48 +1000 Subject: [PATCH 022/165] api.reset: Removed dependency on jQuery --- Src/knockout.validation.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Src/knockout.validation.js b/Src/knockout.validation.js index 4cb77bc4..0762ac56 100644 --- a/Src/knockout.validation.js +++ b/Src/knockout.validation.js @@ -219,7 +219,7 @@ configure: function (options) { exports.init(options); }, // resets the config back to its original state - reset: function () { configuration = jQuery.extend(configuration, defaults); }, + reset: function () { ko.utils.extend(configuration, defaults); }, // recursivly walks a viewModel and creates an object that // provides validation information for the entire viewModel @@ -959,7 +959,7 @@ observable.clearError = function () { observable.error(null); observable.__valid__(true); - } + }; //subscribe to changes in the observable var h_change = observable.subscribe(function () { From e539277acc5ff890145db1bd0f83c954572198cd Mon Sep 17 00:00:00 2001 From: Sergey Bezkostnyi Date: Wed, 4 Sep 2013 09:40:50 +0300 Subject: [PATCH 023/165] Added config option decorateElementOnModified --- Src/knockout.validation.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Src/knockout.validation.js b/Src/knockout.validation.js index 0762ac56..6dc3681c 100644 --- a/Src/knockout.validation.js +++ b/Src/knockout.validation.js @@ -60,6 +60,7 @@ parseInputAttributes: false, // parses the HTML5 validation attribute from a form element and adds that to the object writeInputAttributes: false, // adds HTML5 input validation attributes to form elements that ko observable's are bound to decorateElement: false, // false to keep backward compatibility + decorateElementOnModified: true,// true to keep backward compatibility errorClass: null, // single class for error message and element errorElementClass: 'validationElement', // class to decorate error element errorMessageClass: 'validationMessage', // class to decorate error message @@ -828,7 +829,7 @@ var cssSettingsAccessor = function () { var css = {}; - var shouldShow = (isModified ? !isValid : false); + var shouldShow = ((!config.decorateElementOnModified || isModified) ? !isValid : false); if (!config.decorateElement) { shouldShow = false; } From 1f9bc8b6993333379c0677e6c8dc2247104dc457 Mon Sep 17 00:00:00 2001 From: Sergey Bezkostnyi Date: Wed, 4 Sep 2013 10:06:45 +0300 Subject: [PATCH 024/165] Added tests for config option decorateElementOnModified --- Tests/validation-ui-tests.js | 58 ++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/Tests/validation-ui-tests.js b/Tests/validation-ui-tests.js index 7272f7d1..12ba2863 100644 --- a/Tests/validation-ui-tests.js +++ b/Tests/validation-ui-tests.js @@ -92,6 +92,64 @@ test('Inserting Messages Works', function () { //#endregion +//#region Inserting Messages + +test('Decorating Elements Works', function () { + + addTestHtml(''); + + var vm = { + firstName: ko.observable('').extend({ required: true }) + }; + + // make sure the options are ok. + ko.validation.init({ + decorateElement: true + }, true); + + applyTestBindings(vm); + + var $testInput = $('#myTestInput'); + + ok(!$testInput.hasClass('validationElement'), "CSS class shouldn't present"); + + $testInput.val("a"); //set it + $testInput.change(); //trigger change event + + $testInput.val(""); //set it + $testInput.change(); //trigger change event + + ok($testInput.hasClass('validationElement'), "CSS class should present"); +}); + +test('Decorating Elements On Modified Works', function () { + + addTestHtml(''); + + var vm = { + firstName: ko.observable('').extend({ required: true }) + }; + + // make sure the options are ok. + ko.validation.init({ + decorateElement: true, + decorateElementOnModified: false + }, true); + + applyTestBindings(vm); + + var $testInput = $('#myTestInput'); + + ok($testInput.hasClass('validationElement'), "CSS class should present"); + + $testInput.val("a"); //set it + $testInput.change(); //trigger change event + + ok(!$testInput.hasClass('validationElement'), "CSS class shouldn't present"); +}); + +//#endregion + //#region Showing errors as titles test('Showing Errors As Titles Works', function () { From 813028f479410dd4ed665c40386bd8e023555009 Mon Sep 17 00:00:00 2001 From: thomaswr Date: Sun, 8 Sep 2013 13:12:53 +0200 Subject: [PATCH 025/165] Added German localization --- Localization/de-DE.js | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Localization/de-DE.js diff --git a/Localization/de-DE.js b/Localization/de-DE.js new file mode 100644 index 00000000..259e7029 --- /dev/null +++ b/Localization/de-DE.js @@ -0,0 +1,39 @@ +/// + +/************************************************ +* This is an example localization page. All of these +* messages are the default messages for ko.validation +* +* Currently ko.validation only does a single parameter replacement +* on your message (indicated by the {0}). +* +* The parameter that you provide in your validation extender +* is what is passed to your message to do the {0} replacement. +* +* eg: myProperty.extend({ minLength: 5 }); +* ... will provide a message of "Please enter at least 5 characters" +* when validated +* +* This message replacement obviously only works with primitives +* such as numbers and strings. We do not stringify complex objects +* or anything like that currently. +*/ + +ko.validation.localize({ + required: 'Dieses Feld ist erforderlich.', + min: 'Bitte geben Sie einen Wert größer oder gleich {0} ein.', + max: 'Bitte geben Sie einen Wert kleiner oder gleich {0} ein.', + minLength: 'Bitte geben Sie mindestens {0} Zeichen ein.', + maxLength: 'Bitte geben Sie nicht mehr als {0} Zeichen ein.', + pattern: 'Bitte überprüfen Sie diesen Wert.', + step: 'Der Wert muss um {0} erhöht werden.', + email: 'Das ist keine gültige Email-Adresse.', + date: 'Bitte geben Sie ein gültiges Datum ein.', + dateISO: 'Bitte geben Sie ein gültiges Datum ein.', + number: 'Bitte geben Sie eine Zahl ein.', + digit: 'Bitte geben Sie eine Ziffer ein.', + phoneUS: 'Bitte geben Sie eine gültige Telefonnummer ein.', + equal: 'Die Werte müssen übereinstimmen.', + notEqual: 'Bitte wählen Sie einen anderen Wert.', + unique: 'Bitte stellen Sie sicher, dass der Wert eindeutig ist.' +}); From 3f98cb98da60ab13ae69e846075f85ca95845d90 Mon Sep 17 00:00:00 2001 From: mcliment Date: Wed, 18 Sep 2013 15:11:12 +0200 Subject: [PATCH 026/165] Add viewModel and bindingContext to wrapped init call --- Src/knockout.validation.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Src/knockout.validation.js b/Src/knockout.validation.js index 6dc3681c..6e488b0a 100644 --- a/Src/knockout.validation.js +++ b/Src/knockout.validation.js @@ -512,7 +512,7 @@ ko.bindingHandlers[handlerName].init = function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { - init(element, valueAccessor, allBindingsAccessor); + init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext); return ko.bindingHandlers['validationCore'].init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext); }; From d8173b9fff2d8dedbbe00041536d64b38f75408b Mon Sep 17 00:00:00 2001 From: Josep Seto Date: Tue, 24 Sep 2013 15:14:52 +0200 Subject: [PATCH 027/165] Added Catalan localization --- Localization/ca-CA.js | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Localization/ca-CA.js diff --git a/Localization/ca-CA.js b/Localization/ca-CA.js new file mode 100644 index 00000000..7707c096 --- /dev/null +++ b/Localization/ca-CA.js @@ -0,0 +1,39 @@ +/// + +/************************************************ +* This is an example localization page. All of these +* messages are the default messages for ko.validation +* +* Currently ko.validation only does a single parameter replacement +* on your message (indicated by the {0}). +* +* The parameter that you provide in your validation extender +* is what is passed to your message to do the {0} replacement. +* +* eg: myProperty.extend({ minLength: 5 }); +* ... will provide a message of "Please enter at least 5 characters" +* when validated +* +* This message replacement obviously only works with primitives +* such as numbers and strings. We do not stringify complex objects +* or anything like that currently. +*/ + +ko.validation.localize({ + required: 'Aquest camp es obligatori', + min: 'Introduir un valor igual o major que {0}', + max: 'Introduir un valor menor o igual que {0}', + minLength: 'Ha de tenir un mínim de {0} caràcters', + maxLength: 'No pot tenir mes de {0} caràcters', + pattern: 'Si us plau, comproveu aquest campo', + step: "El valor ha d'incrementar-se en {0}", + email: 'Aquesta no es una adreça de correu electrònic correcta', + date: 'Introduir una data correcta', + dateISO: 'Introduir una data correcta', + number: 'Ha de ser un nombre', + digit: 'Introduir un dígit', + phoneUS: 'Ha de ser un número de telèfon vàlid', + equal: 'Els valors han de ser iguals', + notEqual: 'Elegiu un altre valor', + unique: 'Ha de ser un valor únic' +}); From e16cb8ed0e11937240268a0efbc99e4f7fc0eb7c Mon Sep 17 00:00:00 2001 From: Morten Brix Pedersen Date: Thu, 26 Sep 2013 10:23:28 +0200 Subject: [PATCH 028/165] Add Danish translation. --- Localization/da-DK.js | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Localization/da-DK.js diff --git a/Localization/da-DK.js b/Localization/da-DK.js new file mode 100644 index 00000000..427457c0 --- /dev/null +++ b/Localization/da-DK.js @@ -0,0 +1,39 @@ +/// + +/************************************************ +* This is an example localization page. All of these +* messages are the default messages for ko.validation +* +* Currently ko.validation only does a single parameter replacement +* on your message (indicated by the {0}). +* +* The parameter that you provide in your validation extender +* is what is passed to your message to do the {0} replacement. +* +* eg: myProperty.extend({ minLength: 5 }); +* ... will provide a message of "Please enter at least 5 characters" +* when validated +* +* This message replacement obviously only works with primitives +* such as numbers and strings. We do not stringify complex objects +* or anything like that currently. +*/ + +ko.validation.localize({ + required: 'Dette felt er påkrævet.', + min: 'Angiv en værdi der mindst er {0}.', + max: 'Angiv en værdi der højst er {0}.', + minLength: 'Indtast mindst {0} tegn.', + maxLength: 'Indtast højst {0} tegn.', + pattern: 'Tjek venligst denne værdi.', + step: 'Værdien skal stige med {0}', + email: 'Dette er ikke en gyldig e-mail-adresse', + date: 'Indtast en gyldig dato', + dateISO: 'Indtast en gyldig dato', + number: 'Indtast et tal', + digit: 'Indtast et ciffer', + phoneUS: 'Indtast et gyldigt telefonnummer', + equal: 'Indtast den samme værdi igen.', + notEqual: 'Indtast en anden værdi.', + unique: 'Sørg for at værdien er unik.' +}); From 54f4a416b4b6b10899c57a1c4bd859ff2adc214c Mon Sep 17 00:00:00 2001 From: Tim Larson Date: Tue, 1 Oct 2013 21:04:12 -0400 Subject: [PATCH 029/165] Html5InputAttribute test now waits for async validators to load --- Tests/validation-ui-tests.js | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/Tests/validation-ui-tests.js b/Tests/validation-ui-tests.js index 12ba2863..809e2843 100644 --- a/Tests/validation-ui-tests.js +++ b/Tests/validation-ui-tests.js @@ -604,7 +604,29 @@ test("HTML5 Input types", function () { applyTestBindings(vm); stop(); - setTimeout(function() { + // The validators for the HTML5 Input types are applied asynchronously, + // so we need to wait until the validators have been applied. This is + // done by checking to make sure that the rule has been added to the rules + // list of each observable. + var intervalsWaited = 0; + var intervalId = setInterval(function() { + if (intervalsWaited++ > 1000) { + clearInterval(intervalId); + ok(false, 'Async HTML5 Input validators did not apply within a reasonable amount of time'); + start(); + } + var validatorsReady = + vm.invalidEmail.rules().length > 0 && + vm.invalidDate.rules().length > 0 && + vm.invalidNumber.rules().length > 0; + if (validatorsReady) + runAssertions(); + }, 1); + + function runAssertions() + { + clearInterval(intervalId); + var $emailInput = $('#emailInput'); var emailInput = $emailInput.get(0); var $dateInput = $('#dateInput'); @@ -616,8 +638,8 @@ test("HTML5 Input types", function () { ok(!vm.invalidDate.isValid(), 'Expected date to be considered as invalid.'); ok(!vm.invalidNumber.isValid(), 'Expected date to be considered as invalid.'); - start(); - }, 1 ); + start(); + } }); From b36714713651adbbf3078b56fb7e221809e0c8a5 Mon Sep 17 00:00:00 2001 From: Harry Lascelles Date: Wed, 2 Oct 2013 12:06:47 +0100 Subject: [PATCH 030/165] Passing through additional parameters --- Src/knockout.validation.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Src/knockout.validation.js b/Src/knockout.validation.js index 6e488b0a..1acb3350 100644 --- a/Src/knockout.validation.js +++ b/Src/knockout.validation.js @@ -336,9 +336,9 @@ return result; }, - formatMessage: function (message, params) { + formatMessage: function (message, params, observable) { if (typeof (message) === 'function') { - return message(params); + return message(params, observable); } return message.replace(/\{0\}/gi, ko.utils.unwrapObservable(params)); }, @@ -811,7 +811,7 @@ }; ko.bindingHandlers['validationElement'] = { - update: function (element, valueAccessor) { + update: function (element, valueAccessor, allBindingsAccessor) { var obsv = valueAccessor(), config = utils.getConfigOptions(element), val = ko.utils.unwrapObservable(obsv), @@ -840,7 +840,7 @@ }; //add or remove class on the element; - ko.bindingHandlers.css.update(element, cssSettingsAccessor); + ko.bindingHandlers.css.update(element, cssSettingsAccessor, allBindingsAccessor); if (!config.errorsAsTitle) { return; } var origTitle = utils.getAttribute(element, 'data-orig-title'), @@ -998,7 +998,7 @@ if (!rule.validator(observable(), ctx.params === undefined ? true : ctx.params)) { // default param is true, eg. required = true //not valid, so format the error message and stick it in the 'error' variable - observable.error(exports.formatMessage(ctx.message || rule.message, ctx.params)); + observable.error(exports.formatMessage(ctx.message || rule.message, ctx.params, observable)); observable.__valid__(false); return false; } else { @@ -1031,7 +1031,7 @@ if (!isValid) { //not valid, so format the error message and stick it in the 'error' variable - observable.error(exports.formatMessage(msg || ctx.message || rule.message, ctx.params)); + observable.error(exports.formatMessage(msg || ctx.message || rule.message, ctx.params, observable)); observable.__valid__(isValid); } From aad964276215f53dd566c3ee6a67cb8867b22b8a Mon Sep 17 00:00:00 2001 From: Steve Greatrex Date: Thu, 3 Oct 2013 20:03:05 +0100 Subject: [PATCH 031/165] first steps to a better build: new gruntfile and jshint working+passing --- .gitignore | 2 + .jshintrc | 18 + Lib/knockout-latest.debug.js | 7249 +++++++++++++++-------------- Scripts/_references.js | 1 + Src/knockout.validation.js | 30 +- Tests/{ => Qunit}/jquery-1.7.1.js | 0 Tests/test-runner.htm | 2 +- Tests/validation-tests.js | 38 +- Tests/validation-ui-tests.js | 72 +- grunt.js | 59 - gruntfile.js | 65 + package.json | 32 + 12 files changed, 3859 insertions(+), 3709 deletions(-) create mode 100644 .jshintrc create mode 100644 Scripts/_references.js rename Tests/{ => Qunit}/jquery-1.7.1.js (100%) delete mode 100644 grunt.js create mode 100644 gruntfile.js create mode 100644 package.json diff --git a/.gitignore b/.gitignore index 0dd9a511..21f654f8 100644 --- a/.gitignore +++ b/.gitignore @@ -17,3 +17,5 @@ *.iws target *.ncrunchsolution +node_modules +*.webinfo \ No newline at end of file diff --git a/.jshintrc b/.jshintrc new file mode 100644 index 00000000..541883b6 --- /dev/null +++ b/.jshintrc @@ -0,0 +1,18 @@ +{ + "curly": true, + "eqeqeq": true, + "immed": true, + "latedef": true, + "newcap": true, + "noarg": true, + "sub": true, + "undef": true, + "boss": true, + "eqnull": true, + "browser": true, + "smarttabs": true, + "globals": { + "jQuery": false, + "ko": true + } +} \ No newline at end of file diff --git a/Lib/knockout-latest.debug.js b/Lib/knockout-latest.debug.js index b65eb054..9fe33c8f 100644 --- a/Lib/knockout-latest.debug.js +++ b/Lib/knockout-latest.debug.js @@ -1,3580 +1,3679 @@ -// Knockout JavaScript library v2.2.0 +// Knockout JavaScript library v2.3.0 // (c) Steven Sanderson - http://knockoutjs.com/ // License: MIT (http://www.opensource.org/licenses/mit-license.php) (function () { - var DEBUG = true; - (function (window, document, navigator, jQuery, undefined) { - !function (factory) { - // Support three module loading scenarios - if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') { - // [1] CommonJS/Node.js - var target = module['exports'] || exports; // module.exports is for Node.js - factory(target); - } else if (typeof define === 'function' && define['amd']) { - // [2] AMD anonymous module - define(['exports'], factory); - } else { - // [3] No module loader (plain "); - }; - - if (jQueryTmplVersion > 0) { - jQuery['tmpl']['tag']['ko_code'] = { - open: "__.push($1 || '');" - }; - jQuery['tmpl']['tag']['ko_with'] = { - open: "with($1) {", - close: "} " - }; - } - }; - - ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine(); - - // Use this one by default *only if jquery.tmpl is referenced* - var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine(); - if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0) - ko.setTemplateEngine(jqueryTmplTemplateEngineInstance); - - ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine); - })(); - }); - })(window, document, navigator, window["jQuery"]); + var DEBUG = true; + (function (undefined) { + // (0, eval)('this') is a robust way of getting a reference to the global object + // For details, see http://stackoverflow.com/questions/14119988/return-this-0-evalthis/14120023#14120023 + var window = this || (0, eval)('this'), + document = window['document'], + navigator = window['navigator'], + jQuery = window["jQuery"], + JSON = window["JSON"]; + (function (factory) { + // Support three module loading scenarios + if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') { + // [1] CommonJS/Node.js + var target = module['exports'] || exports; // module.exports is for Node.js + factory(target); + } else if (typeof define === 'function' && define['amd']) { + // [2] AMD anonymous module + define(['exports'], factory); + } else { + // [3] No module loader (plain - + diff --git a/Tests/validation-tests.js b/Tests/validation-tests.js index 1c859736..df6524f5 100644 --- a/Tests/validation-tests.js +++ b/Tests/validation-tests.js @@ -1,6 +1,14 @@ -/// -/// -/// +/*global + module:false, + equal:false, + notEqual:false, + strictEqual:false, + test:false, + ok:false, + asyncTest:false, + start: false, + stop: false +*/ //#region Required Validation @@ -82,7 +90,7 @@ test('Object is Valid and isValid returns True', function () { }); test('Object is Valid and isValid returns True (with min: 0)', function () { - testObj = ko.observable('') + var testObj = ko.observable('') .extend({ min: 0 }); testObj("0"); @@ -822,7 +830,7 @@ test('Issue #78 - Falsy Params', function () { //#endregion //#region Manual Validation -module("Manual Validation") +module("Manual Validation"); test("setError sets isValid and error message", function () { var testObj = ko.observable(); testObj.extend({ validatable: true }); @@ -845,7 +853,7 @@ test("clearError clears manually-specified error", function () { testObj.setError("oh no!"); //fail the validation - ok(!testObj.isValid()) + ok(!testObj.isValid()); //clear the validation testObj.clearError(); @@ -957,7 +965,7 @@ test('Error Grouping works', function () { var errors = ko.validation.group(vm); - equals(errors().length, 2, 'Grouping correctly finds 2 invalid properties'); + equal(errors().length, 2, 'Grouping correctly finds 2 invalid properties'); }); test('Nested Grouping works - Observable', function () { @@ -975,7 +983,7 @@ test('Nested Grouping works - Observable', function () { var errors = ko.validation.group(vm, { deep: true, observable: true }); - equals(errors().length, 3, 'Grouping correctly finds 3 invalid properties'); + equal(errors().length, 3, 'Grouping correctly finds 3 invalid properties'); }); test('Nested Grouping works - Not Observable', function () { @@ -993,7 +1001,7 @@ test('Nested Grouping works - Not Observable', function () { var errors = ko.validation.group(vm, { deep: true, observable: false }); - equals(errors().length, 3, 'Grouping correctly finds 3 invalid properties'); + equal(errors().length, 3, 'Grouping correctly finds 3 invalid properties'); }); test('Issue #31 - Recursively Show All Messages', function () { @@ -1022,7 +1030,7 @@ test('Issue #31 - Recursively Show All Messages', function () { ok(vm.two.one.isModified(), "Level 2 is modified"); ok(vm.three.two.one.isModified(), "Level 3 is modified"); - equals(errors().length, 3, 'Grouping correctly finds 3 invalid properties'); + equal(errors().length, 3, 'Grouping correctly finds 3 invalid properties'); }); test('Issue #31 - Recursively Show All Messages - using computed', function () { @@ -1051,7 +1059,7 @@ test('Issue #31 - Recursively Show All Messages - using computed', function () { ok(vm.two.one.isModified(), "Level 2 is modified"); ok(vm.three.two.one.isModified(), "Level 3 is modified"); - equals(errors().length, 3, 'Grouping correctly finds 3 invalid properties'); + equal(errors().length, 3, 'Grouping correctly finds 3 invalid properties'); }); test('Issue #37 - Toggle ShowAllMessages', function () { @@ -1080,7 +1088,7 @@ test('Issue #37 - Toggle ShowAllMessages', function () { ok(vm.two.one.isModified(), "Level 2 is modified"); ok(vm.three.two.one.isModified(), "Level 3 is modified"); - equals(errors().length, 3, 'Grouping correctly finds 3 invalid properties'); + equal(errors().length, 3, 'Grouping correctly finds 3 invalid properties'); // now shut them off errors.showAllMessages(false); @@ -1105,7 +1113,7 @@ test('Grouping options does not overwrite global configuration options', functio var errors = ko.validation.group(vm); - equals(errors().length, 1, 'Grouping finds one invalid object because deep option was not specified.'); + equal(errors().length, 1, 'Grouping finds one invalid object because deep option was not specified.'); }); test("Issue #235 - formatMessage should unwrap observable parameters", function () { @@ -1153,10 +1161,10 @@ test('Changing the value of observable used in onlyIf condition triggers validat required: { onlyIf: person.isMarried } }); person.isMarried(false); - ok(person.spouseName.isValid(), 'Unmarried person is valid without spouse name') + ok(person.spouseName.isValid(), 'Unmarried person is valid without spouse name'); person.isMarried(true); - equal(person.spouseName.isValid(), false, 'Married person is not valid without spouse name') + equal(person.spouseName.isValid(), false, 'Married person is not valid without spouse name'); }); //#endregion diff --git a/Tests/validation-ui-tests.js b/Tests/validation-ui-tests.js index 7272f7d1..75db9126 100644 --- a/Tests/validation-ui-tests.js +++ b/Tests/validation-ui-tests.js @@ -1,7 +1,15 @@ -/// -/// -/// -/// +/*global + module:false, + equal:false, + notEqual:false, + strictEqual:false, + test:false, + ok:false, + asyncTest:false, + start: false, + stop: false, + $: false +*/ module('UI Tests', { setup: function () { @@ -121,7 +129,7 @@ test('Showing Errors As Titles Works', function () { var isValid = vm.firstName.isValid(); ok(!isValid, 'First Name is NOT Valid'); - console.log($testInput) + var msg = $testInput.attr('title'); equal(msg, 'This field is required.', msg); @@ -157,44 +165,44 @@ test('Original titles are restored', function () { $testInput.val("a"); //set it $testInput.change(); //trigger change event - var msg = $testInput.attr('title'); + msg = $testInput.attr('title'); equal(msg, 'my-orig-title', msg); }); test("Original titles are restored to blank", function () { - addTestHtml(''); + addTestHtml(''); - var vm = { - firstName: ko.observable('').extend({ required: true }) - }; + var vm = { + firstName: ko.observable('').extend({ required: true }) + }; - // make sure the options are ok. - ko.validation.init({ - errorsAsTitleOnModified: true, - decorateElement: true - }, true); + // make sure the options are ok. + ko.validation.init({ + errorsAsTitleOnModified: true, + decorateElement: true + }, true); - applyTestBindings(vm); + applyTestBindings(vm); - var $testInput = $('#myTestInput'); + var $testInput = $('#myTestInput'); - $testInput.val("a"); //set it - $testInput.change(); //trigger change event + $testInput.val("a"); //set it + $testInput.change(); //trigger change event - $testInput.val(""); //set it - $testInput.change(); //trigger change event + $testInput.val(""); //set it + $testInput.change(); //trigger change event - ok(!vm.firstName.isValid(), 'First Name is NOT Valid'); + ok(!vm.firstName.isValid(), 'First Name is NOT Valid'); - //now make the name valid - vm.firstName("valid name"); - ok(vm.firstName.isValid(), "Should now be valid"); + //now make the name valid + vm.firstName("valid name"); + ok(vm.firstName.isValid(), "Should now be valid"); - //and check that the title was reset to blank - var updatedTitle = $testInput.attr("title") - ok(!updatedTitle, "Title should have been reset to blank"); -}) + //and check that the title was reset to blank + var updatedTitle = $testInput.attr("title"); + ok(!updatedTitle, "Title should have been reset to blank"); +}); test('Original titles are restored with multiple validators, too', function () { @@ -226,13 +234,13 @@ test('Original titles are restored with multiple validators, too', function () { $testInput.val("a"); //set it $testInput.change(); //trigger change event - var msg = $testInput.attr('title'); + msg = $testInput.attr('title'); equal(msg, 'Please enter at least 2 characters.', msg); $testInput.val("aa"); //set it $testInput.change(); //trigger change event - var msg = $testInput.attr('title'); + msg = $testInput.attr('title'); equal(msg, 'my-orig-title', msg); }); @@ -265,7 +273,7 @@ test('Showing Errors As Titles is disabled sucessfully', function () { var isValid = vm.firstName.isValid(); ok(!isValid, 'First Name is NOT Valid'); - console.log($testInput) + var msg = $testInput.attr('title'); notEqual(msg, 'This field is required.', msg); diff --git a/grunt.js b/grunt.js deleted file mode 100644 index e194f3d6..00000000 --- a/grunt.js +++ /dev/null @@ -1,59 +0,0 @@ -/*global module:false*/ -module.exports = function (grunt) { - - // Project configuration. - grunt.initConfig({ - meta: { - version: '1.0.2', - banner: '/*\n' + - '===============================================================================\n' + - ' Author: Eric M. Barnard - @ericmbarnard \n' + - ' License: MIT (http://opensource.org/licenses/mit-license.php) \n' + - ' \n' + - ' Description: Validation Library for KnockoutJS \n' + - '===============================================================================\n' + - '*/' - }, - lint: { - files: ['grunt.js', 'src/knockout.validation.js'] - }, - qunit: { - files: ['Tests/test-runner.htm'] - }, - concat: { - dist: { - src: ['', ''], - dest: 'Dist/knockout.validation.js' - } - }, - min: { - dist: { - src: ['', ''], - dest: 'dist/knockout.validation.min.js' - } - }, - jshint: { - options: { - curly: true, - eqeqeq: true, - immed: true, - latedef: true, - newcap: true, - noarg: true, - sub: true, - undef: true, - boss: true, - eqnull: true, - browser: true - }, - globals: { - jQuery: false - } - }, - uglify: {} - }); - - // Default task. - grunt.registerTask('default', 'lint qunit concat min'); - -}; diff --git a/gruntfile.js b/gruntfile.js new file mode 100644 index 00000000..f32a7b4b --- /dev/null +++ b/gruntfile.js @@ -0,0 +1,65 @@ +/*global module:false*/ +module.exports = function (grunt) { + + // Project configuration. + grunt.initConfig({ + pkg: grunt.file.readJSON("package.json"), + meta: { + banner: "/*\n" + + "===============================================================================\n" + + " Author: Eric M. Barnard - @ericmbarnard \n" + + " License: MIT (http://opensource.org/licenses/mit-license.php) \n" + + " \n" + + " Description: Validation Library for KnockoutJS \n" + + "===============================================================================\n" + + "*/" + }, + concat: { + options: { + separator: ";", + banner: "<%= meta.banner %>" + }, + dist: { + src: [ + "<%= meta.banner %>", + "src/<%= pkg.name %>.js", + ], + dest: "dist/<%= pkg.name %>.js" + } + }, + uglify: { + options: { + banner: "<%= meta.banner %>" + }, + dist: { + files: { + "dist/<%= pkg.name %>.min.js": ["<%= concat.dist.dest %>"] + } + } + }, + qunit: { + files: ["Tests/test-runner.htm"] + }, + jshint: { + files: ["src/**/*.js", "Tests/*.js"], + options: grunt.file.readJSON(".jshintrc"), + }, + watch: { + clear: { + files: ["src/**/*.js", "Tests/*.js"], + tasks: ["clear", "test"] + } + } + }); + + grunt.loadNpmTasks("grunt-contrib-uglify"); + grunt.loadNpmTasks("grunt-contrib-jshint"); + grunt.loadNpmTasks("grunt-contrib-qunit"); + grunt.loadNpmTasks("grunt-contrib-concat"); + grunt.loadNpmTasks("grunt-contrib-watch"); + grunt.loadNpmTasks("grunt-clear"); + + // Default task. + grunt.registerTask("default", ["qunit", "jshint", "concat", "uglify"]); + grunt.registerTask("test", ["qunit", "jshint"]); +}; diff --git a/package.json b/package.json new file mode 100644 index 00000000..79452ac7 --- /dev/null +++ b/package.json @@ -0,0 +1,32 @@ +{ + "name": "knockout.validation", + "version": "2.0.0-Pre", + "description": "A KnockoutJS Plugin for model and property validation", + "main": "gruntfile.js", + "dependencies": { + "grunt": "~0.4.1", + "grunt-cli": "~0.1.9" + }, + "devDependencies": { + "grunt": "~0.4.1", + "grunt-cli": "~0.1.9", + "grunt-contrib-jshint": "~0.6.0", + "grunt-contrib-uglify": "~0.2.2", + "grunt-contrib-concat": "~0.3.0", + "grunt-contrib-qunit": "~0.2.2", + "grunt-contrib-watch": "~0.5.3", + "grunt-clear": "~0.2.1" + }, + "scripts": { + "test": "grunt test --verbose" + }, + "repository": { + "type": "git", + "url": "https://github.com/Knockout-Contrib/Knockout-Validation.git" + }, + "author": "@ericmbarnard", + "license": "MIT", + "bugs": { + "url": "https://github.com/Knockout-Contrib/Knockout-Validation/issues" + } +} From a04319d8d0c51d67ba0c294ff18fcb5ad8c11521 Mon Sep 17 00:00:00 2001 From: Steve Greatrex Date: Thu, 3 Oct 2013 20:16:07 +0100 Subject: [PATCH 032/165] gruntfile now fully working - qunit update to fix timeouts --- Dist/knockout.validation.js | 39 +- Dist/knockout.validation.min.js | 13 +- Tests/Qunit/jquery-1.7.1.js | 9266 ------------------- Tests/Qunit/jquery-2.0.3.intellisense.js | 2670 ++++++ Tests/Qunit/jquery-2.0.3.js | 8829 ++++++++++++++++++ Tests/Qunit/{qunit.css => qunit-1.12.0.css} | 71 +- Tests/Qunit/qunit-1.12.0.js | 2212 +++++ Tests/Qunit/qunit.js | 1452 --- Tests/test-runner.htm | 6 +- Tests/validation-tests.js | 6 +- Tests/validation-ui-tests.js | 3 +- gruntfile.js | 6 +- package.json | 2 +- 13 files changed, 13791 insertions(+), 10784 deletions(-) delete mode 100644 Tests/Qunit/jquery-1.7.1.js create mode 100644 Tests/Qunit/jquery-2.0.3.intellisense.js create mode 100644 Tests/Qunit/jquery-2.0.3.js rename Tests/Qunit/{qunit.css => qunit-1.12.0.css} (75%) create mode 100644 Tests/Qunit/qunit-1.12.0.js delete mode 100644 Tests/Qunit/qunit.js diff --git a/Dist/knockout.validation.js b/Dist/knockout.validation.js index e16dd2de..f859b319 100644 --- a/Dist/knockout.validation.js +++ b/Dist/knockout.validation.js @@ -1,28 +1,11 @@ -/* +/*============================================================================= + Author: Eric M. Barnard - @ericmbarnard + License: MIT (http://opensource.org/licenses/mit-license.php) + + Description: Validation Library for KnockoutJS =============================================================================== - Author: Eric M. Barnard - @ericmbarnard - License: MIT (http://opensource.org/licenses/mit-license.php) - - Description: Validation Library for KnockoutJS -=============================================================================== -*/ - -/*jshint - sub:true, - curly: true,eqeqeq: true, - immed: true, - latedef: true, - newcap: true, - noarg: true, - sub: true, - undef: true, - boss: true, - eqnull: true, - browser: true */ - /*globals - jQuery: false, require: false, exports: false, define: false, @@ -947,6 +930,18 @@ return observable.__valid__(); }); + //manually set error state + observable.setError = function (error) { + observable.error(error); + observable.__valid__(false); + }; + + //manually clear error state + observable.clearError = function () { + observable.error(null); + observable.__valid__(true); + }; + //subscribe to changes in the observable var h_change = observable.subscribe(function () { observable.isModified(true); diff --git a/Dist/knockout.validation.min.js b/Dist/knockout.validation.min.js index 27422629..e3de8d95 100644 --- a/Dist/knockout.validation.min.js +++ b/Dist/knockout.validation.min.js @@ -1,9 +1,8 @@ -/* -=============================================================================== - Author: Eric M. Barnard - @ericmbarnard - License: MIT (http://opensource.org/licenses/mit-license.php) - - Description: Validation Library for KnockoutJS +/*============================================================================= + Author: Eric M. Barnard - @ericmbarnard + License: MIT (http://opensource.org/licenses/mit-license.php) + + Description: Validation Library for KnockoutJS =============================================================================== */ -(function(e){typeof require=="function"&&typeof exports=="object"&&typeof module=="object"?e(require("knockout"),exports):typeof define=="function"&&define.amd?define(["knockout","exports"],e):e(ko,ko.validation={})})(function(e,t){function l(e,n,r){return n.validator(e(),r.params===undefined?!0:r.params)?!0:(e.error(t.formatMessage(r.message||n.message,r.params)),e.__valid__(!1),!1)}function c(e,n,r){e.isValidating(!0);var i=function(i){var s=!1,o="";if(!e.__valid__()){e.isValidating(!1);return}i.message?(s=i.isValid,o=i.message):s=i,s||(e.error(t.formatMessage(o||r.message||n.message,r.params)),e.__valid__(s)),e.isValidating(!1)};n.validator(e(),r.params||!0,i)}if(typeof e===undefined)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";var n=t;e.validation=n;var r={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateElement:!1,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",grouping:{deep:!1,observable:!0}},i=e.utils.extend({},r),s=["required","pattern","min","max","step"],o=["email","number","date"],u=function(e){window.setImmediate?window.setImmediate(e):window.setTimeout(e,0)},a=function(){var e=(new Date).getTime(),t={},n="__ko_validation__";return{isArray:function(e){return e.isArray||Object.prototype.toString.call(e)==="[object Array]"},isObject:function(e){return e!==null&&typeof e=="object"},values:function(e){var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(e[n]);return t},getValue:function(e){return typeof e=="function"?e():e},hasAttribute:function(e,t){return e.getAttribute(t)!==null},getAttribute:function(e,t){return e.getAttribute(t)},setAttribute:function(e,t,n){return e.setAttribute(t,n)},isValidatable:function(e){return e&&e.rules&&e.isValid&&e.isModified},insertAfter:function(e,t){e.parentNode.insertBefore(t,e.nextSibling)},newId:function(){return e+=1},getConfigOptions:function(e){var t=a.contextFor(e);return t||i},setDomData:function(e,r){var i=e[n];i||(e[n]=i=a.newId()),t[i]=r},getDomData:function(e){var r=e[n];return r?t[r]:undefined},contextFor:function(e){switch(e.nodeType){case 1:case 8:var t=a.getDomData(e);if(t)return t;if(e.parentNode)return a.contextFor(e.parentNode)}return undefined},isEmptyVal:function(e){if(e===undefined)return!0;if(e===null)return!0;if(e==="")return!0},getOriginalElementTitle:function(e){var t=a.getAttribute(e,"data-orig-title"),n=e.title,r=a.hasAttribute(e,"data-orig-title");return r?t:n}}}(),f=function(){var n=0;return{utils:a,init:function(r,s){if(n>0&&!s)return;r=r||{},r.errorElementClass=r.errorElementClass||r.errorClass||i.errorElementClass,r.errorMessageClass=r.errorMessageClass||r.errorClass||i.errorMessageClass,e.utils.extend(i,r),i.registerExtenders&&t.registerExtenders(),n=1},configure:function(e){t.init(e)},reset:function(){i=jQuery.extend(i,r)},group:function(n,r){r=e.utils.extend(e.utils.extend({},i.grouping),r);var s=e.observableArray([]),o=null,u=function f(t,n){var i=[],o=e.utils.unwrapObservable(t);n=n!==undefined?n:r.deep?1:-1,e.isObservable(t)&&(t.isValid||t.extend({validatable:!0}),s.push(t)),o&&(a.isArray(o)?i=o:a.isObject(o)&&(i=a.values(o))),n!==0&&e.utils.arrayForEach(i,function(e){e&&!e.nodeType&&f(e,n+1)})};return r.observable?(u(n),o=e.computed(function(){var t=[];return e.utils.arrayForEach(s(),function(e){e.isValid()||t.push(e.error)}),t})):o=function(){var t=[];return s([]),u(n),e.utils.arrayForEach(s(),function(e){e.isValid()||t.push(e.error)}),t},o.showAllMessages=function(t){t===undefined&&(t=!0),o(),e.utils.arrayForEach(s(),function(e){e.isModified(t)})},n.errors=o,n.isValid=function(){return n.errors().length===0},n.isAnyMessageShown=function(){var t=!1;return o(),e.utils.arrayForEach(s(),function(e){!e.isValid()&&e.isModified()&&(t=!0)}),t},o},formatMessage:function(t,n){return typeof t=="function"?t(n):t.replace(/\{0\}/gi,e.utils.unwrapObservable(n))},addRule:function(e,t){return e.extend({validatable:!0}),e.rules.push(t),e},addAnonymousRule:function(e,n){var r=a.newId();n.message===undefined&&(n.message="Error"),t.rules[r]=n,t.addRule(e,{rule:r,params:n.params})},addExtender:function(n){e.extenders[n]=function(e,r){return r.message||r.onlyIf?t.addRule(e,{rule:n,message:r.message,params:a.isEmptyVal(r.params)?!0:r.params,condition:r.onlyIf}):t.addRule(e,{rule:n,params:r})}},registerExtenders:function(){if(i.registerExtenders)for(var n in t.rules)t.rules.hasOwnProperty(n)&&(e.extenders[n]||t.addExtender(n))},insertValidationMessage:function(e){var t=document.createElement("SPAN");return t.className=a.getConfigOptions(e).errorMessageClass,a.insertAfter(e,t),t},parseInputValidationAttributes:function(n,r){e.utils.arrayForEach(s,function(e){a.hasAttribute(n,e)&&t.addRule(r(),{rule:e,params:n.getAttribute(e)||!0})});var i=n.getAttribute("type");e.utils.arrayForEach(o,function(e){e===i&&t.addRule(r(),{rule:e==="date"?"dateISO":e,params:!0})})},writeInputValidationAttributes:function(t,n){var r=n();if(!r||!r.rules)return;var i=r.rules();e.utils.arrayForEach(s,function(n){var r,s=e.utils.arrayFirst(i,function(e){return e.rule.toLowerCase()===n.toLowerCase()});if(!s)return;r=s.params,s.rule==="pattern"&&s.params instanceof RegExp&&(r=s.params.source),t.setAttribute(n,r)}),i=null},makeBindingHandlerValidatable:function(t){var n=e.bindingHandlers[t].init;e.bindingHandlers[t].init=function(t,r,i,s,o){return n(t,r,i),e.bindingHandlers.validationCore.init(t,r,i,s,o)}}}}();e.utils.extend(n,f),n.rules={},n.rules.required={validator:function(e,t){var n=/^\s+|\s+$/g,r;return e===undefined||e===null?!t:(r=e,typeof e=="string"&&(r=e.replace(n,"")),t?(r+"").length>0:!0)},message:"This field is required."},n.rules.min={validator:function(e,t){return a.isEmptyVal(e)||e>=t},message:"Please enter a value greater than or equal to {0}."},n.rules.max={validator:function(e,t){return a.isEmptyVal(e)||e<=t},message:"Please enter a value less than or equal to {0}."},n.rules.minLength={validator:function(e,t){return a.isEmptyVal(e)||e.length>=t},message:"Please enter at least {0} characters."},n.rules.maxLength={validator:function(e,t){return a.isEmptyVal(e)||e.length<=t},message:"Please enter no more than {0} characters."},n.rules.pattern={validator:function(e,t){return a.isEmptyVal(e)||e.toString().match(t)!==null},message:"Please check this value."},n.rules.step={validator:function(e,t){return a.isEmptyVal(e)||e*100%(t*100)===0},message:"The value must increment by {0}"},n.rules.email={validator:function(e,t){return t?a.isEmptyVal(e)||t&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(e):!0},message:"Please enter a proper email address"},n.rules.date={validator:function(e,t){return t?a.isEmptyVal(e)||t&&!/Invalid|NaN/.test(new Date(e)):!0},message:"Please enter a proper date"},n.rules.dateISO={validator:function(e,t){return t?a.isEmptyVal(e)||t&&/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(e):!0},message:"Please enter a proper date"},n.rules.number={validator:function(e,t){return t?a.isEmptyVal(e)||t&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(e):!0},message:"Please enter a number"},n.rules.digit={validator:function(e,t){return t?a.isEmptyVal(e)||t&&/^\d+$/.test(e):!0},message:"Please enter a digit"},n.rules.phoneUS={validator:function(e,t){return t?typeof e!="string"?!1:a.isEmptyVal(e)?!0:(e=e.replace(/\s+/g,""),t&&e.length>9&&e.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number"},n.rules.equal={validator:function(e,t){var n=t;return e===a.getValue(n)},message:"Values must equal"},n.rules.notEqual={validator:function(e,t){var n=t;return e!==a.getValue(n)},message:"Please choose another value."},n.rules.unique={validator:function(t,n){var r=a.getValue(n.collection),i=a.getValue(n.externalValue),s=0;return!t||!r?!0:(e.utils.arrayFilter(e.utils.unwrapObservable(r),function(e){t===(n.valueAccessor?n.valueAccessor(e):e)&&s++}),s<(i!==undefined&&t!==i?1:2))},message:"Please make sure the value is unique."},function(){n.registerExtenders()}(),e.bindingHandlers.validationCore=function(){return{init:function(n,r,i,s,o){var f=a.getConfigOptions(n);f.parseInputAttributes&&u(function(){t.parseInputValidationAttributes(n,r)});if(f.insertMessages&&a.isValidatable(r())){var l=t.insertValidationMessage(n);f.messageTemplate?e.renderTemplate(f.messageTemplate,{field:r()},null,l,"replaceNode"):e.applyBindingsToNode(l,{validationMessage:r()})}f.writeInputAttributes&&a.isValidatable(r())&&t.writeInputValidationAttributes(n,r),f.decorateElement&&a.isValidatable(r())&&e.applyBindingsToNode(n,{validationElement:r()})},update:function(e,t,n,r,i){}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),e.bindingHandlers.validationMessage={update:function(t,n){var r=n(),i=a.getConfigOptions(t),s=e.utils.unwrapObservable(r),o=null,u=!1,f=!1;r.extend({validatable:!0}),u=r.isModified(),f=r.isValid();var l=function(){return!i.messagesOnModified||u?f?null:r.error:null},c=function(){return!i.messagesOnModified||u?!f:!1};e.bindingHandlers.text.update(t,l),e.bindingHandlers.visible.update(t,c)}},e.bindingHandlers.validationElement={update:function(t,n){var r=n(),i=a.getConfigOptions(t),s=e.utils.unwrapObservable(r),o=null,u=!1,f=!1;r.extend({validatable:!0}),u=r.isModified(),f=r.isValid();var l=function(){var e={},t=u?!f:!1;return i.decorateElement||(t=!1),e[i.errorElementClass]=t,e};e.bindingHandlers.css.update(t,l);if(!i.errorsAsTitle)return;var c=a.getAttribute(t,"data-orig-title"),h=t.title,p=a.getAttribute(t,"data-orig-title")==="true",d=function(){if(!i.errorsAsTitleOnModified||u)return f?{title:a.getOriginalElementTitle(t),"data-orig-title":null}:{title:r.error,"data-orig-title":a.getOriginalElementTitle(t)}};e.bindingHandlers.attr.update(t,d)}},e.bindingHandlers.validationOptions=function(){return{init:function(t,n,r,s,o){var u=e.utils.unwrapObservable(n());if(u){var f=e.utils.extend({},i);e.utils.extend(f,u),a.setDomData(t,f)}}}}(),e.extenders.validation=function(n,r){return e.utils.arrayForEach(a.isArray(r)?r:[r],function(e){t.addAnonymousRule(n,e)}),n},e.extenders.validatable=function(n,r){if(r&&!a.isValidatable(n)){n.error=e.observable(null),n.rules=e.observableArray(),n.isValidating=e.observable(!1),n.__valid__=e.observable(!0),n.isModified=e.observable(!1);var i=e.computed(function(){var e=n(),r=n.rules();return t.validateObservable(n),!0});n.isValid=e.computed(function(){return n.__valid__()});var s=n.subscribe(function(){n.isModified(!0)});n._disposeValidation=function(){n.isValid.dispose(),n.rules.removeAll(),n.isModified._subscriptions.change=[],n.isValidating._subscriptions.change=[],n.__valid__._subscriptions.change=[],s.dispose(),i.dispose(),delete n.rules,delete n.error,delete n.isValid,delete n.isValidating,delete n.__valid__,delete n.isModified}}else r===!1&&a.isValidatable(n)&&n._disposeValidation&&n._disposeValidation();return n},n.validateObservable=function(e){var n=0,r,i,s=e.rules(),o=s.length;for(;n2?(o=r,u=i):s<2?o=document.body:arguments[1].nodeType?o=r:u=arguments[1],t.init(),u&&t.utils.setDomData(o,u),e.applyBindings(n,r)};var h=e.applyBindings;e.applyBindings=function(e,n){t.init(),h(e,n)}}); \ No newline at end of file +!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a,c,d){return c.validator(a(),void 0===d.params?!0:d.params)?!0:(a.error(b.formatMessage(d.message||c.message,d.params)),a.__valid__(!1),!1)}function d(a,c,d){a.isValidating(!0);var e=function(e){var f=!1,g="";return a.__valid__()?(e.message?(f=e.isValid,g=e.message):f=e,f||(a.error(b.formatMessage(g||d.message||c.message,d.params)),a.__valid__(f)),a.isValidating(!1),void 0):(a.isValidating(!1),void 0)};c.validator(a(),d.params||!0,e)}if(void 0===typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";var e=b;a.validation=e;var f={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateElement:!1,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",grouping:{deep:!1,observable:!0}},g=a.utils.extend({},f),h=["required","pattern","min","max","step"],i=["email","number","date"],j=function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},k=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return a&&a.rules&&a.isValid&&a.isModified},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=k.contextFor(a);return b||g},setDomData:function(a,d){var e=a[c];e||(a[c]=e=k.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=k.getDomData(a);if(b)return b;if(a.parentNode)return k.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=k.getAttribute(a,"data-orig-title"),c=a.title,d=k.hasAttribute(a,"data-orig-title");return d?b:c}}}(),l=function(){var c=0;return{utils:k,init:function(d,e){c>0&&!e||(d=d||{},d.errorElementClass=d.errorElementClass||d.errorClass||g.errorElementClass,d.errorMessageClass=d.errorMessageClass||d.errorClass||g.errorMessageClass,a.utils.extend(g,d),g.registerExtenders&&b.registerExtenders(),c=1)},configure:function(a){b.init(a)},reset:function(){g=jQuery.extend(g,f)},group:function(b,c){c=a.utils.extend(a.utils.extend({},g.grouping),c);var d=a.observableArray([]),e=null,f=function h(b,e){var f=[],g=a.utils.unwrapObservable(b);e=void 0!==e?e:c.deep?1:-1,a.isObservable(b)&&(b.isValid||b.extend({validatable:!0}),d.push(b)),g&&(k.isArray(g)?f=g:k.isObject(g)&&(f=k.values(g))),0!==e&&a.utils.arrayForEach(f,function(a){a&&!a.nodeType&&h(a,e+1)})};return c.observable?(f(b),e=a.computed(function(){var b=[];return a.utils.arrayForEach(d(),function(a){a.isValid()||b.push(a.error)}),b})):e=function(){var c=[];return d([]),f(b),a.utils.arrayForEach(d(),function(a){a.isValid()||c.push(a.error)}),c},e.showAllMessages=function(b){void 0===b&&(b=!0),e(),a.utils.arrayForEach(d(),function(a){a.isModified(b)})},b.errors=e,b.isValid=function(){return 0===b.errors().length},b.isAnyMessageShown=function(){var b=!1;return e(),a.utils.arrayForEach(d(),function(a){!a.isValid()&&a.isModified()&&(b=!0)}),b},e},formatMessage:function(b,c){return"function"==typeof b?b(c):b.replace(/\{0\}/gi,a.utils.unwrapObservable(c))},addRule:function(a,b){return a.extend({validatable:!0}),a.rules.push(b),a},addAnonymousRule:function(a,c){var d=k.newId();void 0===c.message&&(c.message="Error"),b.rules[d]=c,b.addRule(a,{rule:d,params:c.params})},addExtender:function(c){a.extenders[c]=function(a,d){return d.message||d.onlyIf?b.addRule(a,{rule:c,message:d.message,params:k.isEmptyVal(d.params)?!0:d.params,condition:d.onlyIf}):b.addRule(a,{rule:c,params:d})}},registerExtenders:function(){if(g.registerExtenders)for(var c in b.rules)b.rules.hasOwnProperty(c)&&(a.extenders[c]||b.addExtender(c))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=k.getConfigOptions(a).errorMessageClass,k.insertAfter(a,b),b},parseInputValidationAttributes:function(c,d){a.utils.arrayForEach(h,function(a){k.hasAttribute(c,a)&&b.addRule(d(),{rule:a,params:c.getAttribute(a)||!0})});var e=c.getAttribute("type");a.utils.arrayForEach(i,function(a){a===e&&b.addRule(d(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(b,c){var d=c();if(d&&d.rules){var e=d.rules();a.utils.arrayForEach(h,function(c){var d,f=a.utils.arrayFirst(e,function(a){return a.rule.toLowerCase()===c.toLowerCase()});f&&(d=f.params,"pattern"===f.rule&&f.params instanceof RegExp&&(d=f.params.source),b.setAttribute(c,d))}),e=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e),a.bindingHandlers.validationCore.init(b,d,e,f,g)}}}}();a.utils.extend(e,l),e.rules={},e.rules.required={validator:function(a,b){var c,d=/^\s+|\s+$/g;return void 0===a||null===a?!b:(c=a,"string"==typeof a&&(c=a.replace(d,"")),b?(c+"").length>0:!0)},message:"This field is required."},e.rules.min={validator:function(a,b){return k.isEmptyVal(a)||a>=b},message:"Please enter a value greater than or equal to {0}."},e.rules.max={validator:function(a,b){return k.isEmptyVal(a)||b>=a},message:"Please enter a value less than or equal to {0}."},e.rules.minLength={validator:function(a,b){return k.isEmptyVal(a)||a.length>=b},message:"Please enter at least {0} characters."},e.rules.maxLength={validator:function(a,b){return k.isEmptyVal(a)||a.length<=b},message:"Please enter no more than {0} characters."},e.rules.pattern={validator:function(a,b){return k.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},e.rules.step={validator:function(a,b){return k.isEmptyVal(a)||0===100*a%(100*b)},message:"The value must increment by {0}"},e.rules.email={validator:function(a,b){return b?k.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address"},e.rules.date={validator:function(a,b){return b?k.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date"},e.rules.dateISO={validator:function(a,b){return b?k.isEmptyVal(a)||b&&/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(a):!0},message:"Please enter a proper date"},e.rules.number={validator:function(a,b){return b?k.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(a):!0},message:"Please enter a number"},e.rules.digit={validator:function(a,b){return b?k.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit"},e.rules.phoneUS={validator:function(a,b){return b?"string"!=typeof a?!1:k.isEmptyVal(a)?!0:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number"},e.rules.equal={validator:function(a,b){var c=b;return a===k.getValue(c)},message:"Values must equal"},e.rules.notEqual={validator:function(a,b){var c=b;return a!==k.getValue(c)},message:"Please choose another value."},e.rules.unique={validator:function(b,c){var d=k.getValue(c.collection),e=k.getValue(c.externalValue),f=0;return b&&d?(a.utils.arrayFilter(a.utils.unwrapObservable(d),function(a){b===(c.valueAccessor?c.valueAccessor(a):a)&&f++}),(void 0!==e&&b!==e?1:2)>f):!0},message:"Please make sure the value is unique."},function(){e.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(c,d){var e=k.getConfigOptions(c);if(e.parseInputAttributes&&j(function(){b.parseInputValidationAttributes(c,d)}),e.insertMessages&&k.isValidatable(d())){var f=b.insertValidationMessage(c);e.messageTemplate?a.renderTemplate(e.messageTemplate,{field:d()},null,f,"replaceNode"):a.applyBindingsToNode(f,{validationMessage:d()})}e.writeInputAttributes&&k.isValidatable(d())&&b.writeInputValidationAttributes(c,d),e.decorateElement&&k.isValidatable(d())&&a.applyBindingsToNode(c,{validationElement:d()})},update:function(){}}}(),l.makeBindingHandlerValidatable("value"),l.makeBindingHandlerValidatable("checked"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=k.getConfigOptions(b),f=(a.utils.unwrapObservable(d),!1),g=!1;d.extend({validatable:!0}),f=d.isModified(),g=d.isValid();var h=function(){return!e.messagesOnModified||f?g?null:d.error:null},i=function(){return!e.messagesOnModified||f?!g:!1};a.bindingHandlers.text.update(b,h),a.bindingHandlers.visible.update(b,i)}},a.bindingHandlers.validationElement={update:function(b,c){var d=c(),e=k.getConfigOptions(b),f=(a.utils.unwrapObservable(d),!1),g=!1;d.extend({validatable:!0}),f=d.isModified(),g=d.isValid();var h=function(){var a={},b=f?!g:!1;return e.decorateElement||(b=!1),a[e.errorElementClass]=b,a};if(a.bindingHandlers.css.update(b,h),e.errorsAsTitle){k.getAttribute(b,"data-orig-title"),b.title,"true"===k.getAttribute(b,"data-orig-title");var i=function(){return!e.errorsAsTitleOnModified||f?g?{title:k.getOriginalElementTitle(b),"data-orig-title":null}:{title:d.error,"data-orig-title":k.getOriginalElementTitle(b)}:void 0};a.bindingHandlers.attr.update(b,i)}}},a.bindingHandlers.validationOptions=function(){return{init:function(b,c){var d=a.utils.unwrapObservable(c());if(d){var e=a.utils.extend({},g);a.utils.extend(e,d),k.setDomData(b,e)}}}}(),a.extenders.validation=function(c,d){return a.utils.arrayForEach(k.isArray(d)?d:[d],function(a){b.addAnonymousRule(c,a)}),c},a.extenders.validatable=function(c,d){if(d&&!k.isValidatable(c)){c.error=a.observable(null),c.rules=a.observableArray(),c.isValidating=a.observable(!1),c.__valid__=a.observable(!0),c.isModified=a.observable(!1);var e=a.computed(function(){return c(),c.rules(),b.validateObservable(c),!0});c.isValid=a.computed(function(){return c.__valid__()}),c.setError=function(a){c.error(a),c.__valid__(!1)},c.clearError=function(){c.error(null),c.__valid__(!0)};var f=c.subscribe(function(){c.isModified(!0)});c._disposeValidation=function(){c.isValid.dispose(),c.rules.removeAll(),c.isModified._subscriptions.change=[],c.isValidating._subscriptions.change=[],c.__valid__._subscriptions.change=[],f.dispose(),e.dispose(),delete c.rules,delete c.error,delete c.isValid,delete c.isValidating,delete c.__valid__,delete c.isModified}}else d===!1&&k.isValidatable(c)&&c._disposeValidation&&c._disposeValidation();return c},e.validateObservable=function(a){for(var e,f,g=0,h=a.rules(),i=h.length;i>g;g++)if(f=h[g],!f.condition||f.condition())if(e=b.rules[f.rule],e.async||f.async)d(a,e,f);else if(!c(a,e,f))return!1;return a.error(null),a.__valid__(!0),!0},a.validatedObservable=function(c){if(!b.utils.isObject(c))return a.observable(c).extend({validatable:!0});var d=a.observable(c);return d.errors=b.group(c),d.isValid=a.computed(function(){return 0===d.errors().length}),d},e.localize=function(a){var c;for(c in a)b.rules.hasOwnProperty(c)&&(b.rules[c].message=a[c])},a.applyBindingsWithValidation=function(c,d,e){var f,g,h=arguments.length;h>2?(f=d,g=e):2>h?f=document.body:arguments[1].nodeType?f=d:g=arguments[1],b.init(),g&&b.utils.setDomData(f,g),a.applyBindings(c,d)};var m=a.applyBindings;a.applyBindings=function(a,c){b.init(),m(a,c)}}); \ No newline at end of file diff --git a/Tests/Qunit/jquery-1.7.1.js b/Tests/Qunit/jquery-1.7.1.js deleted file mode 100644 index c7017a38..00000000 --- a/Tests/Qunit/jquery-1.7.1.js +++ /dev/null @@ -1,9266 +0,0 @@ -/*! -* jQuery JavaScript Library v1.7.1 -* http://jquery.com/ -* -* Copyright 2011, John Resig -* Dual licensed under the MIT or GPL Version 2 licenses. -* http://jquery.org/license -* -* Includes Sizzle.js -* http://sizzlejs.com/ -* Copyright 2011, The Dojo Foundation -* Released under the MIT, BSD, and GPL Licenses. -* -* Date: Mon Nov 21 21:11:03 2011 -0500 -*/ -(function (window, undefined) { - - // Use the correct document accordingly with window argument (sandbox) - var document = window.document, - navigator = window.navigator, - location = window.location; - var jQuery = (function () { - - // Define a local copy of jQuery - var jQuery = function (selector, context) { - // The jQuery object is actually just the init constructor 'enhanced' - return new jQuery.fn.init(selector, context, rootjQuery); - }, - - // Map over jQuery in case of overwrite - _jQuery = window.jQuery, - - // Map over the $ in case of overwrite - _$ = window.$, - - // A central reference to the root jQuery(document) - rootjQuery, - - // A simple way to check for HTML strings or ID strings - // Prioritize #id over to avoid XSS via location.hash (#9521) - quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, - - // Check if a string has a non-whitespace character in it - rnotwhite = /\S/, - - // Used for trimming whitespace - trimLeft = /^\s+/, - trimRight = /\s+$/, - - // Match a standalone tag - rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, - - // JSON RegExp - rvalidchars = /^[\],:{}\s]*$/, - rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, - rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, - rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, - - // Useragent RegExp - rwebkit = /(webkit)[ \/]([\w.]+)/, - ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, - rmsie = /(msie) ([\w.]+)/, - rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, - - // Matches dashed string for camelizing - rdashAlpha = /-([a-z]|[0-9])/ig, - rmsPrefix = /^-ms-/, - - // Used by jQuery.camelCase as callback to replace() - fcamelCase = function (all, letter) { - return (letter + "").toUpperCase(); - }, - - // Keep a UserAgent string for use with jQuery.browser - userAgent = navigator.userAgent, - - // For matching the engine and version of the browser - browserMatch, - - // The deferred used on DOM ready - readyList, - - // The ready event handler - DOMContentLoaded, - - // Save a reference to some core methods - toString = Object.prototype.toString, - hasOwn = Object.prototype.hasOwnProperty, - push = Array.prototype.push, - slice = Array.prototype.slice, - trim = String.prototype.trim, - indexOf = Array.prototype.indexOf, - - // [[Class]] -> type pairs - class2type = {}; - - jQuery.fn = jQuery.prototype = { - constructor: jQuery, - init: function (selector, context, rootjQuery) { - var match, elem, ret, doc; - - // Handle $(""), $(null), or $(undefined) - if (!selector) { - return this; - } - - // Handle $(DOMElement) - if (selector.nodeType) { - this.context = this[0] = selector; - this.length = 1; - return this; - } - - // The body element only exists once, optimize finding it - if (selector === "body" && !context && document.body) { - this.context = document; - this[0] = document.body; - this.selector = selector; - this.length = 1; - return this; - } - - // Handle HTML strings - if (typeof selector === "string") { - // Are we dealing with HTML string or an ID? - if (selector.charAt(0) === "<" && selector.charAt(selector.length - 1) === ">" && selector.length >= 3) { - // Assume that strings that start and end with <> are HTML and skip the regex check - match = [null, selector, null]; - - } else { - match = quickExpr.exec(selector); - } - - // Verify a match, and that no context was specified for #id - if (match && (match[1] || !context)) { - - // HANDLE: $(html) -> $(array) - if (match[1]) { - context = context instanceof jQuery ? context[0] : context; - doc = (context ? context.ownerDocument || context : document); - - // If a single string is passed in and it's a single tag - // just do a createElement and skip the rest - ret = rsingleTag.exec(selector); - - if (ret) { - if (jQuery.isPlainObject(context)) { - selector = [document.createElement(ret[1])]; - jQuery.fn.attr.call(selector, context, true); - - } else { - selector = [doc.createElement(ret[1])]; - } - - } else { - ret = jQuery.buildFragment([match[1]], [doc]); - selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes; - } - - return jQuery.merge(this, selector); - - // HANDLE: $("#id") - } else { - elem = document.getElementById(match[2]); - - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if (elem && elem.parentNode) { - // Handle the case where IE and Opera return items - // by name instead of ID - if (elem.id !== match[2]) { - return rootjQuery.find(selector); - } - - // Otherwise, we inject the element directly into the jQuery object - this.length = 1; - this[0] = elem; - } - - this.context = document; - this.selector = selector; - return this; - } - - // HANDLE: $(expr, $(...)) - } else if (!context || context.jquery) { - return (context || rootjQuery).find(selector); - - // HANDLE: $(expr, context) - // (which is just equivalent to: $(context).find(expr) - } else { - return this.constructor(context).find(selector); - } - - // HANDLE: $(function) - // Shortcut for document ready - } else if (jQuery.isFunction(selector)) { - return rootjQuery.ready(selector); - } - - if (selector.selector !== undefined) { - this.selector = selector.selector; - this.context = selector.context; - } - - return jQuery.makeArray(selector, this); - }, - - // Start with an empty selector - selector: "", - - // The current version of jQuery being used - jquery: "1.7.1", - - // The default length of a jQuery object is 0 - length: 0, - - // The number of elements contained in the matched element set - size: function () { - return this.length; - }, - - toArray: function () { - return slice.call(this, 0); - }, - - // Get the Nth element in the matched element set OR - // Get the whole matched element set as a clean array - get: function (num) { - return num == null ? - - // Return a 'clean' array - this.toArray() : - - // Return just the object - (num < 0 ? this[this.length + num] : this[num]); - }, - - // Take an array of elements and push it onto the stack - // (returning the new matched element set) - pushStack: function (elems, name, selector) { - // Build a new jQuery matched element set - var ret = this.constructor(); - - if (jQuery.isArray(elems)) { - push.apply(ret, elems); - - } else { - jQuery.merge(ret, elems); - } - - // Add the old object onto the stack (as a reference) - ret.prevObject = this; - - ret.context = this.context; - - if (name === "find") { - ret.selector = this.selector + (this.selector ? " " : "") + selector; - } else if (name) { - ret.selector = this.selector + "." + name + "(" + selector + ")"; - } - - // Return the newly-formed element set - return ret; - }, - - // Execute a callback for every element in the matched set. - // (You can seed the arguments with an array of args, but this is - // only used internally.) - each: function (callback, args) { - return jQuery.each(this, callback, args); - }, - - ready: function (fn) { - // Attach the listeners - jQuery.bindReady(); - - // Add the callback - readyList.add(fn); - - return this; - }, - - eq: function (i) { - i = +i; - return i === -1 ? - this.slice(i) : - this.slice(i, i + 1); - }, - - first: function () { - return this.eq(0); - }, - - last: function () { - return this.eq(-1); - }, - - slice: function () { - return this.pushStack(slice.apply(this, arguments), - "slice", slice.call(arguments).join(",")); - }, - - map: function (callback) { - return this.pushStack(jQuery.map(this, function (elem, i) { - return callback.call(elem, i, elem); - })); - }, - - end: function () { - return this.prevObject || this.constructor(null); - }, - - // For internal use only. - // Behaves like an Array's method, not like a jQuery method. - push: push, - sort: [].sort, - splice: [].splice - }; - - // Give the init function the jQuery prototype for later instantiation - jQuery.fn.init.prototype = jQuery.fn; - - jQuery.extend = jQuery.fn.extend = function () { - var options, name, src, copy, copyIsArray, clone, - target = arguments[0] || {}, - i = 1, - length = arguments.length, - deep = false; - - // Handle a deep copy situation - if (typeof target === "boolean") { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } - - // Handle case when target is a string or something (possible in deep copy) - if (typeof target !== "object" && !jQuery.isFunction(target)) { - target = {}; - } - - // extend jQuery itself if only one argument is passed - if (length === i) { - target = this; - --i; - } - - for (; i < length; i++) { - // Only deal with non-null/undefined values - if ((options = arguments[i]) != null) { - // Extend the base object - for (name in options) { - src = target[name]; - copy = options[name]; - - // Prevent never-ending loop - if (target === copy) { - continue; - } - - // Recurse if we're merging plain objects or arrays - if (deep && copy && (jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)))) { - if (copyIsArray) { - copyIsArray = false; - clone = src && jQuery.isArray(src) ? src : []; - - } else { - clone = src && jQuery.isPlainObject(src) ? src : {}; - } - - // Never move original objects, clone them - target[name] = jQuery.extend(deep, clone, copy); - - // Don't bring in undefined values - } else if (copy !== undefined) { - target[name] = copy; - } - } - } - } - - // Return the modified object - return target; - }; - - jQuery.extend({ - noConflict: function (deep) { - if (window.$ === jQuery) { - window.$ = _$; - } - - if (deep && window.jQuery === jQuery) { - window.jQuery = _jQuery; - } - - return jQuery; - }, - - // Is the DOM ready to be used? Set to true once it occurs. - isReady: false, - - // A counter to track how many items to wait for before - // the ready event fires. See #6781 - readyWait: 1, - - // Hold (or release) the ready event - holdReady: function (hold) { - if (hold) { - jQuery.readyWait++; - } else { - jQuery.ready(true); - } - }, - - // Handle when the DOM is ready - ready: function (wait) { - // Either a released hold or an DOMready/load event and not yet ready - if ((wait === true && ! --jQuery.readyWait) || (wait !== true && !jQuery.isReady)) { - // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). - if (!document.body) { - return setTimeout(jQuery.ready, 1); - } - - // Remember that the DOM is ready - jQuery.isReady = true; - - // If a normal DOM Ready event fired, decrement, and wait if need be - if (wait !== true && --jQuery.readyWait > 0) { - return; - } - - // If there are functions bound, to execute - readyList.fireWith(document, [jQuery]); - - // Trigger any bound ready events - if (jQuery.fn.trigger) { - jQuery(document).trigger("ready").off("ready"); - } - } - }, - - bindReady: function () { - if (readyList) { - return; - } - - readyList = jQuery.Callbacks("once memory"); - - // Catch cases where $(document).ready() is called after the - // browser event has already occurred. - if (document.readyState === "complete") { - // Handle it asynchronously to allow scripts the opportunity to delay ready - return setTimeout(jQuery.ready, 1); - } - - // Mozilla, Opera and webkit nightlies currently support this event - if (document.addEventListener) { - // Use the handy event callback - document.addEventListener("DOMContentLoaded", DOMContentLoaded, false); - - // A fallback to window.onload, that will always work - window.addEventListener("load", jQuery.ready, false); - - // If IE event model is used - } else if (document.attachEvent) { - // ensure firing before onload, - // maybe late but safe also for iframes - document.attachEvent("onreadystatechange", DOMContentLoaded); - - // A fallback to window.onload, that will always work - window.attachEvent("onload", jQuery.ready); - - // If IE and not a frame - // continually check to see if the document is ready - var toplevel = false; - - try { - toplevel = window.frameElement == null; - } catch (e) { } - - if (document.documentElement.doScroll && toplevel) { - doScrollCheck(); - } - } - }, - - // See test/unit/core.js for details concerning isFunction. - // Since version 1.3, DOM methods and functions like alert - // aren't supported. They return false on IE (#2968). - isFunction: function (obj) { - return jQuery.type(obj) === "function"; - }, - - isArray: Array.isArray || function (obj) { - return jQuery.type(obj) === "array"; - }, - - // A crude way of determining if an object is a window - isWindow: function (obj) { - return obj && typeof obj === "object" && "setInterval" in obj; - }, - - isNumeric: function (obj) { - return !isNaN(parseFloat(obj)) && isFinite(obj); - }, - - type: function (obj) { - return obj == null ? - String(obj) : - class2type[toString.call(obj)] || "object"; - }, - - isPlainObject: function (obj) { - // Must be an Object. - // Because of IE, we also have to check the presence of the constructor property. - // Make sure that DOM nodes and window objects don't pass through, as well - if (!obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow(obj)) { - return false; - } - - try { - // Not own constructor property must be Object - if (obj.constructor && - !hasOwn.call(obj, "constructor") && - !hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) { - return false; - } - } catch (e) { - // IE8,9 Will throw exceptions on certain host objects #9897 - return false; - } - - // Own properties are enumerated firstly, so to speed up, - // if last one is own, then all properties are own. - - var key; - for (key in obj) { } - - return key === undefined || hasOwn.call(obj, key); - }, - - isEmptyObject: function (obj) { - for (var name in obj) { - return false; - } - return true; - }, - - error: function (msg) { - throw new Error(msg); - }, - - parseJSON: function (data) { - if (typeof data !== "string" || !data) { - return null; - } - - // Make sure leading/trailing whitespace is removed (IE can't handle it) - data = jQuery.trim(data); - - // Attempt to parse using the native JSON parser first - if (window.JSON && window.JSON.parse) { - return window.JSON.parse(data); - } - - // Make sure the incoming data is actual JSON - // Logic borrowed from http://json.org/json2.js - if (rvalidchars.test(data.replace(rvalidescape, "@") - .replace(rvalidtokens, "]") - .replace(rvalidbraces, ""))) { - - return (new Function("return " + data))(); - - } - jQuery.error("Invalid JSON: " + data); - }, - - // Cross-browser xml parsing - parseXML: function (data) { - var xml, tmp; - try { - if (window.DOMParser) { // Standard - tmp = new DOMParser(); - xml = tmp.parseFromString(data, "text/xml"); - } else { // IE - xml = new ActiveXObject("Microsoft.XMLDOM"); - xml.async = "false"; - xml.loadXML(data); - } - } catch (e) { - xml = undefined; - } - if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) { - jQuery.error("Invalid XML: " + data); - } - return xml; - }, - - noop: function () { }, - - // Evaluates a script in a global context - // Workarounds based on findings by Jim Driscoll - // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context - globalEval: function (data) { - if (data && rnotwhite.test(data)) { - // We use execScript on Internet Explorer - // We use an anonymous function so that context is window - // rather than jQuery in Firefox - (window.execScript || function (data) { - window["eval"].call(window, data); - })(data); - } - }, - - // Convert dashed to camelCase; used by the css and data modules - // Microsoft forgot to hump their vendor prefix (#9572) - camelCase: function (string) { - return string.replace(rmsPrefix, "ms-").replace(rdashAlpha, fcamelCase); - }, - - nodeName: function (elem, name) { - return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); - }, - - // args is for internal usage only - each: function (object, callback, args) { - var name, i = 0, - length = object.length, - isObj = length === undefined || jQuery.isFunction(object); - - if (args) { - if (isObj) { - for (name in object) { - if (callback.apply(object[name], args) === false) { - break; - } - } - } else { - for (; i < length; ) { - if (callback.apply(object[i++], args) === false) { - break; - } - } - } - - // A special, fast, case for the most common use of each - } else { - if (isObj) { - for (name in object) { - if (callback.call(object[name], name, object[name]) === false) { - break; - } - } - } else { - for (; i < length; ) { - if (callback.call(object[i], i, object[i++]) === false) { - break; - } - } - } - } - - return object; - }, - - // Use native String.trim function wherever possible - trim: trim ? - function (text) { - return text == null ? - "" : - trim.call(text); - } : - - // Otherwise use our own trimming functionality - function (text) { - return text == null ? - "" : - text.toString().replace(trimLeft, "").replace(trimRight, ""); - }, - - // results is for internal usage only - makeArray: function (array, results) { - var ret = results || []; - - if (array != null) { - // The window, strings (and functions) also have 'length' - // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 - var type = jQuery.type(array); - - if (array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow(array)) { - push.call(ret, array); - } else { - jQuery.merge(ret, array); - } - } - - return ret; - }, - - inArray: function (elem, array, i) { - var len; - - if (array) { - if (indexOf) { - return indexOf.call(array, elem, i); - } - - len = array.length; - i = i ? i < 0 ? Math.max(0, len + i) : i : 0; - - for (; i < len; i++) { - // Skip accessing in sparse arrays - if (i in array && array[i] === elem) { - return i; - } - } - } - - return -1; - }, - - merge: function (first, second) { - var i = first.length, - j = 0; - - if (typeof second.length === "number") { - for (var l = second.length; j < l; j++) { - first[i++] = second[j]; - } - - } else { - while (second[j] !== undefined) { - first[i++] = second[j++]; - } - } - - first.length = i; - - return first; - }, - - grep: function (elems, callback, inv) { - var ret = [], retVal; - inv = !!inv; - - // Go through the array, only saving the items - // that pass the validator function - for (var i = 0, length = elems.length; i < length; i++) { - retVal = !!callback(elems[i], i); - if (inv !== retVal) { - ret.push(elems[i]); - } - } - - return ret; - }, - - // arg is for internal usage only - map: function (elems, callback, arg) { - var value, key, ret = [], - i = 0, - length = elems.length, - // jquery objects are treated as arrays - isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ((length > 0 && elems[0] && elems[length - 1]) || length === 0 || jQuery.isArray(elems)); - - // Go through the array, translating each of the items to their - if (isArray) { - for (; i < length; i++) { - value = callback(elems[i], i, arg); - - if (value != null) { - ret[ret.length] = value; - } - } - - // Go through every key on the object, - } else { - for (key in elems) { - value = callback(elems[key], key, arg); - - if (value != null) { - ret[ret.length] = value; - } - } - } - - // Flatten any nested arrays - return ret.concat.apply([], ret); - }, - - // A global GUID counter for objects - guid: 1, - - // Bind a function to a context, optionally partially applying any - // arguments. - proxy: function (fn, context) { - if (typeof context === "string") { - var tmp = fn[context]; - context = fn; - fn = tmp; - } - - // Quick check to determine if target is callable, in the spec - // this throws a TypeError, but we will just return undefined. - if (!jQuery.isFunction(fn)) { - return undefined; - } - - // Simulated bind - var args = slice.call(arguments, 2), - proxy = function () { - return fn.apply(context, args.concat(slice.call(arguments))); - }; - - // Set the guid of unique handler to the same of original handler, so it can be removed - proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; - - return proxy; - }, - - // Mutifunctional method to get and set values to a collection - // The value/s can optionally be executed if it's a function - access: function (elems, key, value, exec, fn, pass) { - var length = elems.length; - - // Setting many attributes - if (typeof key === "object") { - for (var k in key) { - jQuery.access(elems, k, key[k], exec, fn, value); - } - return elems; - } - - // Setting one attribute - if (value !== undefined) { - // Optionally, function values get executed if exec is true - exec = !pass && exec && jQuery.isFunction(value); - - for (var i = 0; i < length; i++) { - fn(elems[i], key, exec ? value.call(elems[i], i, fn(elems[i], key)) : value, pass); - } - - return elems; - } - - // Getting an attribute - return length ? fn(elems[0], key) : undefined; - }, - - now: function () { - return (new Date()).getTime(); - }, - - // Use of jQuery.browser is frowned upon. - // More details: http://docs.jquery.com/Utilities/jQuery.browser - uaMatch: function (ua) { - ua = ua.toLowerCase(); - - var match = rwebkit.exec(ua) || - ropera.exec(ua) || - rmsie.exec(ua) || - ua.indexOf("compatible") < 0 && rmozilla.exec(ua) || - []; - - return { browser: match[1] || "", version: match[2] || "0" }; - }, - - sub: function () { - function jQuerySub(selector, context) { - return new jQuerySub.fn.init(selector, context); - } - jQuery.extend(true, jQuerySub, this); - jQuerySub.superclass = this; - jQuerySub.fn = jQuerySub.prototype = this(); - jQuerySub.fn.constructor = jQuerySub; - jQuerySub.sub = this.sub; - jQuerySub.fn.init = function init(selector, context) { - if (context && context instanceof jQuery && !(context instanceof jQuerySub)) { - context = jQuerySub(context); - } - - return jQuery.fn.init.call(this, selector, context, rootjQuerySub); - }; - jQuerySub.fn.init.prototype = jQuerySub.fn; - var rootjQuerySub = jQuerySub(document); - return jQuerySub; - }, - - browser: {} - }); - - // Populate the class2type map - jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function (i, name) { - class2type["[object " + name + "]"] = name.toLowerCase(); - }); - - browserMatch = jQuery.uaMatch(userAgent); - if (browserMatch.browser) { - jQuery.browser[browserMatch.browser] = true; - jQuery.browser.version = browserMatch.version; - } - - // Deprecated, use jQuery.browser.webkit instead - if (jQuery.browser.webkit) { - jQuery.browser.safari = true; - } - - // IE doesn't match non-breaking spaces with \s - if (rnotwhite.test("\xA0")) { - trimLeft = /^[\s\xA0]+/; - trimRight = /[\s\xA0]+$/; - } - - // All jQuery objects should point back to these - rootjQuery = jQuery(document); - - // Cleanup functions for the document ready method - if (document.addEventListener) { - DOMContentLoaded = function () { - document.removeEventListener("DOMContentLoaded", DOMContentLoaded, false); - jQuery.ready(); - }; - - } else if (document.attachEvent) { - DOMContentLoaded = function () { - // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). - if (document.readyState === "complete") { - document.detachEvent("onreadystatechange", DOMContentLoaded); - jQuery.ready(); - } - }; - } - - // The DOM ready check for Internet Explorer - function doScrollCheck() { - if (jQuery.isReady) { - return; - } - - try { - // If IE is used, use the trick by Diego Perini - // http://javascript.nwbox.com/IEContentLoaded/ - document.documentElement.doScroll("left"); - } catch (e) { - setTimeout(doScrollCheck, 1); - return; - } - - // and execute any waiting functions - jQuery.ready(); - } - - return jQuery; - - })(); - - - // String to Object flags format cache - var flagsCache = {}; - - // Convert String-formatted flags into Object-formatted ones and store in cache - function createFlags(flags) { - var object = flagsCache[flags] = {}, - i, length; - flags = flags.split(/\s+/); - for (i = 0, length = flags.length; i < length; i++) { - object[flags[i]] = true; - } - return object; - } - - /* - * Create a callback list using the following parameters: - * - * flags: an optional list of space-separated flags that will change how - * the callback list behaves - * - * By default a callback list will act like an event callback list and can be - * "fired" multiple times. - * - * Possible flags: - * - * once: will ensure the callback list can only be fired once (like a Deferred) - * - * memory: will keep track of previous values and will call any callback added - * after the list has been fired right away with the latest "memorized" - * values (like a Deferred) - * - * unique: will ensure a callback can only be added once (no duplicate in the list) - * - * stopOnFalse: interrupt callings when a callback returns false - * - */ - jQuery.Callbacks = function (flags) { - - // Convert flags from String-formatted to Object-formatted - // (we check in cache first) - flags = flags ? (flagsCache[flags] || createFlags(flags)) : {}; - - var // Actual callback list - list = [], - // Stack of fire calls for repeatable lists - stack = [], - // Last fire value (for non-forgettable lists) - memory, - // Flag to know if list is currently firing - firing, - // First callback to fire (used internally by add and fireWith) - firingStart, - // End of the loop when firing - firingLength, - // Index of currently firing callback (modified by remove if needed) - firingIndex, - // Add one or several callbacks to the list - add = function (args) { - var i, - length, - elem, - type, - actual; - for (i = 0, length = args.length; i < length; i++) { - elem = args[i]; - type = jQuery.type(elem); - if (type === "array") { - // Inspect recursively - add(elem); - } else if (type === "function") { - // Add if not in unique mode and callback is not in - if (!flags.unique || !self.has(elem)) { - list.push(elem); - } - } - } - }, - // Fire callbacks - fire = function (context, args) { - args = args || []; - memory = !flags.memory || [context, args]; - firing = true; - firingIndex = firingStart || 0; - firingStart = 0; - firingLength = list.length; - for (; list && firingIndex < firingLength; firingIndex++) { - if (list[firingIndex].apply(context, args) === false && flags.stopOnFalse) { - memory = true; // Mark as halted - break; - } - } - firing = false; - if (list) { - if (!flags.once) { - if (stack && stack.length) { - memory = stack.shift(); - self.fireWith(memory[0], memory[1]); - } - } else if (memory === true) { - self.disable(); - } else { - list = []; - } - } - }, - // Actual Callbacks object - self = { - // Add a callback or a collection of callbacks to the list - add: function () { - if (list) { - var length = list.length; - add(arguments); - // Do we need to add the callbacks to the - // current firing batch? - if (firing) { - firingLength = list.length; - // With memory, if we're not firing then - // we should call right away, unless previous - // firing was halted (stopOnFalse) - } else if (memory && memory !== true) { - firingStart = length; - fire(memory[0], memory[1]); - } - } - return this; - }, - // Remove a callback from the list - remove: function () { - if (list) { - var args = arguments, - argIndex = 0, - argLength = args.length; - for (; argIndex < argLength; argIndex++) { - for (var i = 0; i < list.length; i++) { - if (args[argIndex] === list[i]) { - // Handle firingIndex and firingLength - if (firing) { - if (i <= firingLength) { - firingLength--; - if (i <= firingIndex) { - firingIndex--; - } - } - } - // Remove the element - list.splice(i--, 1); - // If we have some unicity property then - // we only need to do this once - if (flags.unique) { - break; - } - } - } - } - } - return this; - }, - // Control if a given callback is in the list - has: function (fn) { - if (list) { - var i = 0, - length = list.length; - for (; i < length; i++) { - if (fn === list[i]) { - return true; - } - } - } - return false; - }, - // Remove all callbacks from the list - empty: function () { - list = []; - return this; - }, - // Have the list do nothing anymore - disable: function () { - list = stack = memory = undefined; - return this; - }, - // Is it disabled? - disabled: function () { - return !list; - }, - // Lock the list in its current state - lock: function () { - stack = undefined; - if (!memory || memory === true) { - self.disable(); - } - return this; - }, - // Is it locked? - locked: function () { - return !stack; - }, - // Call all callbacks with the given context and arguments - fireWith: function (context, args) { - if (stack) { - if (firing) { - if (!flags.once) { - stack.push([context, args]); - } - } else if (!(flags.once && memory)) { - fire(context, args); - } - } - return this; - }, - // Call all the callbacks with the given arguments - fire: function () { - self.fireWith(this, arguments); - return this; - }, - // To know if the callbacks have already been called at least once - fired: function () { - return !!memory; - } - }; - - return self; - }; - - - - - var // Static reference to slice - sliceDeferred = [].slice; - - jQuery.extend({ - - Deferred: function (func) { - var doneList = jQuery.Callbacks("once memory"), - failList = jQuery.Callbacks("once memory"), - progressList = jQuery.Callbacks("memory"), - state = "pending", - lists = { - resolve: doneList, - reject: failList, - notify: progressList - }, - promise = { - done: doneList.add, - fail: failList.add, - progress: progressList.add, - - state: function () { - return state; - }, - - // Deprecated - isResolved: doneList.fired, - isRejected: failList.fired, - - then: function (doneCallbacks, failCallbacks, progressCallbacks) { - deferred.done(doneCallbacks).fail(failCallbacks).progress(progressCallbacks); - return this; - }, - always: function () { - deferred.done.apply(deferred, arguments).fail.apply(deferred, arguments); - return this; - }, - pipe: function (fnDone, fnFail, fnProgress) { - return jQuery.Deferred(function (newDefer) { - jQuery.each({ - done: [fnDone, "resolve"], - fail: [fnFail, "reject"], - progress: [fnProgress, "notify"] - }, function (handler, data) { - var fn = data[0], - action = data[1], - returned; - if (jQuery.isFunction(fn)) { - deferred[handler](function () { - returned = fn.apply(this, arguments); - if (returned && jQuery.isFunction(returned.promise)) { - returned.promise().then(newDefer.resolve, newDefer.reject, newDefer.notify); - } else { - newDefer[action + "With"](this === deferred ? newDefer : this, [returned]); - } - }); - } else { - deferred[handler](newDefer[action]); - } - }); - }).promise(); - }, - // Get a promise for this deferred - // If obj is provided, the promise aspect is added to the object - promise: function (obj) { - if (obj == null) { - obj = promise; - } else { - for (var key in promise) { - obj[key] = promise[key]; - } - } - return obj; - } - }, - deferred = promise.promise({}), - key; - - for (key in lists) { - deferred[key] = lists[key].fire; - deferred[key + "With"] = lists[key].fireWith; - } - - // Handle state - deferred.done(function () { - state = "resolved"; - }, failList.disable, progressList.lock).fail(function () { - state = "rejected"; - }, doneList.disable, progressList.lock); - - // Call given func if any - if (func) { - func.call(deferred, deferred); - } - - // All done! - return deferred; - }, - - // Deferred helper - when: function (firstParam) { - var args = sliceDeferred.call(arguments, 0), - i = 0, - length = args.length, - pValues = new Array(length), - count = length, - pCount = length, - deferred = length <= 1 && firstParam && jQuery.isFunction(firstParam.promise) ? - firstParam : - jQuery.Deferred(), - promise = deferred.promise(); - function resolveFunc(i) { - return function (value) { - args[i] = arguments.length > 1 ? sliceDeferred.call(arguments, 0) : value; - if (!(--count)) { - deferred.resolveWith(deferred, args); - } - }; - } - function progressFunc(i) { - return function (value) { - pValues[i] = arguments.length > 1 ? sliceDeferred.call(arguments, 0) : value; - deferred.notifyWith(promise, pValues); - }; - } - if (length > 1) { - for (; i < length; i++) { - if (args[i] && args[i].promise && jQuery.isFunction(args[i].promise)) { - args[i].promise().then(resolveFunc(i), deferred.reject, progressFunc(i)); - } else { - --count; - } - } - if (!count) { - deferred.resolveWith(deferred, args); - } - } else if (deferred !== firstParam) { - deferred.resolveWith(deferred, length ? [firstParam] : []); - } - return promise; - } - }); - - - - - jQuery.support = (function () { - - var support, - all, - a, - select, - opt, - input, - marginDiv, - fragment, - tds, - events, - eventName, - i, - isSupported, - div = document.createElement("div"), - documentElement = document.documentElement; - - // Preliminary tests - div.setAttribute("className", "t"); - div.innerHTML = "
a"; - - all = div.getElementsByTagName("*"); - a = div.getElementsByTagName("a")[0]; - - // Can't get basic test support - if (!all || !all.length || !a) { - return {}; - } - - // First batch of supports tests - select = document.createElement("select"); - opt = select.appendChild(document.createElement("option")); - input = div.getElementsByTagName("input")[0]; - - support = { - // IE strips leading whitespace when .innerHTML is used - leadingWhitespace: (div.firstChild.nodeType === 3), - - // Make sure that tbody elements aren't automatically inserted - // IE will insert them into empty tables - tbody: !div.getElementsByTagName("tbody").length, - - // Make sure that link elements get serialized correctly by innerHTML - // This requires a wrapper element in IE - htmlSerialize: !!div.getElementsByTagName("link").length, - - // Get the style information from getAttribute - // (IE uses .cssText instead) - style: /top/.test(a.getAttribute("style")), - - // Make sure that URLs aren't manipulated - // (IE normalizes it by default) - hrefNormalized: (a.getAttribute("href") === "/a"), - - // Make sure that element opacity exists - // (IE uses filter instead) - // Use a regex to work around a WebKit issue. See #5145 - opacity: /^0.55/.test(a.style.opacity), - - // Verify style float existence - // (IE uses styleFloat instead of cssFloat) - cssFloat: !!a.style.cssFloat, - - // Make sure that if no value is specified for a checkbox - // that it defaults to "on". - // (WebKit defaults to "" instead) - checkOn: (input.value === "on"), - - // Make sure that a selected-by-default option has a working selected property. - // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) - optSelected: opt.selected, - - // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) - getSetAttribute: div.className !== "t", - - // Tests for enctype support on a form(#6743) - enctype: !!document.createElement("form").enctype, - - // Makes sure cloning an html5 element does not cause problems - // Where outerHTML is undefined, this still works - html5Clone: document.createElement("nav").cloneNode(true).outerHTML !== "<:nav>", - - // Will be defined later - submitBubbles: true, - changeBubbles: true, - focusinBubbles: false, - deleteExpando: true, - noCloneEvent: true, - inlineBlockNeedsLayout: false, - shrinkWrapBlocks: false, - reliableMarginRight: true - }; - - // Make sure checked status is properly cloned - input.checked = true; - support.noCloneChecked = input.cloneNode(true).checked; - - // Make sure that the options inside disabled selects aren't marked as disabled - // (WebKit marks them as disabled) - select.disabled = true; - support.optDisabled = !opt.disabled; - - // Test to see if it's possible to delete an expando from an element - // Fails in Internet Explorer - try { - delete div.test; - } catch (e) { - support.deleteExpando = false; - } - - if (!div.addEventListener && div.attachEvent && div.fireEvent) { - div.attachEvent("onclick", function () { - // Cloning a node shouldn't copy over any - // bound event handlers (IE does this) - support.noCloneEvent = false; - }); - div.cloneNode(true).fireEvent("onclick"); - } - - // Check if a radio maintains its value - // after being appended to the DOM - input = document.createElement("input"); - input.value = "t"; - input.setAttribute("type", "radio"); - support.radioValue = input.value === "t"; - - input.setAttribute("checked", "checked"); - div.appendChild(input); - fragment = document.createDocumentFragment(); - fragment.appendChild(div.lastChild); - - // WebKit doesn't clone checked state correctly in fragments - support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked; - - // Check if a disconnected checkbox will retain its checked - // value of true after appended to the DOM (IE6/7) - support.appendChecked = input.checked; - - fragment.removeChild(input); - fragment.appendChild(div); - - div.innerHTML = ""; - - // Check if div with explicit width and no margin-right incorrectly - // gets computed margin-right based on width of container. For more - // info see bug #3333 - // Fails in WebKit before Feb 2011 nightlies - // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right - if (window.getComputedStyle) { - marginDiv = document.createElement("div"); - marginDiv.style.width = "0"; - marginDiv.style.marginRight = "0"; - div.style.width = "2px"; - div.appendChild(marginDiv); - support.reliableMarginRight = - (parseInt((window.getComputedStyle(marginDiv, null) || { marginRight: 0 }).marginRight, 10) || 0) === 0; - } - - // Technique from Juriy Zaytsev - // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ - // We only care about the case where non-standard event systems - // are used, namely in IE. Short-circuiting here helps us to - // avoid an eval call (in setAttribute) which can cause CSP - // to go haywire. See: https://developer.mozilla.org/en/Security/CSP - if (div.attachEvent) { - for (i in { - submit: 1, - change: 1, - focusin: 1 - }) { - eventName = "on" + i; - isSupported = (eventName in div); - if (!isSupported) { - div.setAttribute(eventName, "return;"); - isSupported = (typeof div[eventName] === "function"); - } - support[i + "Bubbles"] = isSupported; - } - } - - fragment.removeChild(div); - - // Null elements to avoid leaks in IE - fragment = select = opt = marginDiv = div = input = null; - - // Run tests that need a body at doc ready - jQuery(function () { - var container, outer, inner, table, td, offsetSupport, - conMarginTop, ptlm, vb, style, html, - body = document.getElementsByTagName("body")[0]; - - if (!body) { - // Return for frameset docs that don't have a body - return; - } - - conMarginTop = 1; - ptlm = "position:absolute;top:0;left:0;width:1px;height:1px;margin:0;"; - vb = "visibility:hidden;border:0;"; - style = "style='" + ptlm + "border:5px solid #000;padding:0;'"; - html = "
" + - "" + - "
"; - - container = document.createElement("div"); - container.style.cssText = vb + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px"; - body.insertBefore(container, body.firstChild); - - // Construct the test element - div = document.createElement("div"); - container.appendChild(div); - - // Check if table cells still have offsetWidth/Height when they are set - // to display:none and there are still other visible table cells in a - // table row; if so, offsetWidth/Height are not reliable for use when - // determining if an element has been hidden directly using - // display:none (it is still safe to use offsets if a parent element is - // hidden; don safety goggles and see bug #4512 for more information). - // (only IE 8 fails this test) - div.innerHTML = "
t
"; - tds = div.getElementsByTagName("td"); - isSupported = (tds[0].offsetHeight === 0); - - tds[0].style.display = ""; - tds[1].style.display = "none"; - - // Check if empty table cells still have offsetWidth/Height - // (IE <= 8 fail this test) - support.reliableHiddenOffsets = isSupported && (tds[0].offsetHeight === 0); - - // Figure out if the W3C box model works as expected - div.innerHTML = ""; - div.style.width = div.style.paddingLeft = "1px"; - jQuery.boxModel = support.boxModel = div.offsetWidth === 2; - - if (typeof div.style.zoom !== "undefined") { - // Check if natively block-level elements act like inline-block - // elements when setting their display to 'inline' and giving - // them layout - // (IE < 8 does this) - div.style.display = "inline"; - div.style.zoom = 1; - support.inlineBlockNeedsLayout = (div.offsetWidth === 2); - - // Check if elements with layout shrink-wrap their children - // (IE 6 does this) - div.style.display = ""; - div.innerHTML = "
"; - support.shrinkWrapBlocks = (div.offsetWidth !== 2); - } - - div.style.cssText = ptlm + vb; - div.innerHTML = html; - - outer = div.firstChild; - inner = outer.firstChild; - td = outer.nextSibling.firstChild.firstChild; - - offsetSupport = { - doesNotAddBorder: (inner.offsetTop !== 5), - doesAddBorderForTableAndCells: (td.offsetTop === 5) - }; - - inner.style.position = "fixed"; - inner.style.top = "20px"; - - // safari subtracts parent border width here which is 5px - offsetSupport.fixedPosition = (inner.offsetTop === 20 || inner.offsetTop === 15); - inner.style.position = inner.style.top = ""; - - outer.style.overflow = "hidden"; - outer.style.position = "relative"; - - offsetSupport.subtractsBorderForOverflowNotVisible = (inner.offsetTop === -5); - offsetSupport.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== conMarginTop); - - body.removeChild(container); - div = container = null; - - jQuery.extend(support, offsetSupport); - }); - - return support; - })(); - - - - - var rbrace = /^(?:\{.*\}|\[.*\])$/, - rmultiDash = /([A-Z])/g; - - jQuery.extend({ - cache: {}, - - // Please use with caution - uuid: 0, - - // Unique for each copy of jQuery on the page - // Non-digits removed to match rinlinejQuery - expando: "jQuery" + (jQuery.fn.jquery + Math.random()).replace(/\D/g, ""), - - // The following elements throw uncatchable exceptions if you - // attempt to add expando properties to them. - noData: { - "embed": true, - // Ban all objects except for Flash (which handle expandos) - "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", - "applet": true - }, - - hasData: function (elem) { - elem = elem.nodeType ? jQuery.cache[elem[jQuery.expando]] : elem[jQuery.expando]; - return !!elem && !isEmptyDataObject(elem); - }, - - data: function (elem, name, data, pvt /* Internal Use Only */) { - if (!jQuery.acceptData(elem)) { - return; - } - - var privateCache, thisCache, ret, - internalKey = jQuery.expando, - getByName = typeof name === "string", - - // We have to handle DOM nodes and JS objects differently because IE6-7 - // can't GC object references properly across the DOM-JS boundary - isNode = elem.nodeType, - - // Only DOM nodes need the global jQuery cache; JS object data is - // attached directly to the object so GC can occur automatically - cache = isNode ? jQuery.cache : elem, - - // Only defining an ID for JS objects if its cache already exists allows - // the code to shortcut on the same path as a DOM node with no cache - id = isNode ? elem[internalKey] : elem[internalKey] && internalKey, - isEvents = name === "events"; - - // Avoid doing any more work than we need to when trying to get data on an - // object that has no data at all - if ((!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined) { - return; - } - - if (!id) { - // Only DOM nodes need a new unique ID for each element since their data - // ends up in the global cache - if (isNode) { - elem[internalKey] = id = ++jQuery.uuid; - } else { - id = internalKey; - } - } - - if (!cache[id]) { - cache[id] = {}; - - // Avoids exposing jQuery metadata on plain JS objects when the object - // is serialized using JSON.stringify - if (!isNode) { - cache[id].toJSON = jQuery.noop; - } - } - - // An object can be passed to jQuery.data instead of a key/value pair; this gets - // shallow copied over onto the existing cache - if (typeof name === "object" || typeof name === "function") { - if (pvt) { - cache[id] = jQuery.extend(cache[id], name); - } else { - cache[id].data = jQuery.extend(cache[id].data, name); - } - } - - privateCache = thisCache = cache[id]; - - // jQuery data() is stored in a separate object inside the object's internal data - // cache in order to avoid key collisions between internal data and user-defined - // data. - if (!pvt) { - if (!thisCache.data) { - thisCache.data = {}; - } - - thisCache = thisCache.data; - } - - if (data !== undefined) { - thisCache[jQuery.camelCase(name)] = data; - } - - // Users should not attempt to inspect the internal events object using jQuery.data, - // it is undocumented and subject to change. But does anyone listen? No. - if (isEvents && !thisCache[name]) { - return privateCache.events; - } - - // Check for both converted-to-camel and non-converted data property names - // If a data property was specified - if (getByName) { - - // First Try to find as-is property data - ret = thisCache[name]; - - // Test for null|undefined property data - if (ret == null) { - - // Try to find the camelCased property - ret = thisCache[jQuery.camelCase(name)]; - } - } else { - ret = thisCache; - } - - return ret; - }, - - removeData: function (elem, name, pvt /* Internal Use Only */) { - if (!jQuery.acceptData(elem)) { - return; - } - - var thisCache, i, l, - - // Reference to internal data cache key - internalKey = jQuery.expando, - - isNode = elem.nodeType, - - // See jQuery.data for more information - cache = isNode ? jQuery.cache : elem, - - // See jQuery.data for more information - id = isNode ? elem[internalKey] : internalKey; - - // If there is already no cache entry for this object, there is no - // purpose in continuing - if (!cache[id]) { - return; - } - - if (name) { - - thisCache = pvt ? cache[id] : cache[id].data; - - if (thisCache) { - - // Support array or space separated string names for data keys - if (!jQuery.isArray(name)) { - - // try the string as a key before any manipulation - if (name in thisCache) { - name = [name]; - } else { - - // split the camel cased version by spaces unless a key with the spaces exists - name = jQuery.camelCase(name); - if (name in thisCache) { - name = [name]; - } else { - name = name.split(" "); - } - } - } - - for (i = 0, l = name.length; i < l; i++) { - delete thisCache[name[i]]; - } - - // If there is no data left in the cache, we want to continue - // and let the cache object itself get destroyed - if (!(pvt ? isEmptyDataObject : jQuery.isEmptyObject)(thisCache)) { - return; - } - } - } - - // See jQuery.data for more information - if (!pvt) { - delete cache[id].data; - - // Don't destroy the parent cache unless the internal data object - // had been the only thing left in it - if (!isEmptyDataObject(cache[id])) { - return; - } - } - - // Browsers that fail expando deletion also refuse to delete expandos on - // the window, but it will allow it on all other JS objects; other browsers - // don't care - // Ensure that `cache` is not a window object #10080 - if (jQuery.support.deleteExpando || !cache.setInterval) { - delete cache[id]; - } else { - cache[id] = null; - } - - // We destroyed the cache and need to eliminate the expando on the node to avoid - // false lookups in the cache for entries that no longer exist - if (isNode) { - // IE does not allow us to delete expando properties from nodes, - // nor does it have a removeAttribute function on Document nodes; - // we must handle all of these cases - if (jQuery.support.deleteExpando) { - delete elem[internalKey]; - } else if (elem.removeAttribute) { - elem.removeAttribute(internalKey); - } else { - elem[internalKey] = null; - } - } - }, - - // For internal use only. - _data: function (elem, name, data) { - return jQuery.data(elem, name, data, true); - }, - - // A method for determining if a DOM node can handle the data expando - acceptData: function (elem) { - if (elem.nodeName) { - var match = jQuery.noData[elem.nodeName.toLowerCase()]; - - if (match) { - return !(match === true || elem.getAttribute("classid") !== match); - } - } - - return true; - } - }); - - jQuery.fn.extend({ - data: function (key, value) { - var parts, attr, name, - data = null; - - if (typeof key === "undefined") { - if (this.length) { - data = jQuery.data(this[0]); - - if (this[0].nodeType === 1 && !jQuery._data(this[0], "parsedAttrs")) { - attr = this[0].attributes; - for (var i = 0, l = attr.length; i < l; i++) { - name = attr[i].name; - - if (name.indexOf("data-") === 0) { - name = jQuery.camelCase(name.substring(5)); - - dataAttr(this[0], name, data[name]); - } - } - jQuery._data(this[0], "parsedAttrs", true); - } - } - - return data; - - } else if (typeof key === "object") { - return this.each(function () { - jQuery.data(this, key); - }); - } - - parts = key.split("."); - parts[1] = parts[1] ? "." + parts[1] : ""; - - if (value === undefined) { - data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); - - // Try to fetch any internally stored data first - if (data === undefined && this.length) { - data = jQuery.data(this[0], key); - data = dataAttr(this[0], key, data); - } - - return data === undefined && parts[1] ? - this.data(parts[0]) : - data; - - } else { - return this.each(function () { - var self = jQuery(this), - args = [parts[0], value]; - - self.triggerHandler("setData" + parts[1] + "!", args); - jQuery.data(this, key, value); - self.triggerHandler("changeData" + parts[1] + "!", args); - }); - } - }, - - removeData: function (key) { - return this.each(function () { - jQuery.removeData(this, key); - }); - } - }); - - function dataAttr(elem, key, data) { - // If nothing was found internally, try to fetch any - // data from the HTML5 data-* attribute - if (data === undefined && elem.nodeType === 1) { - - var name = "data-" + key.replace(rmultiDash, "-$1").toLowerCase(); - - data = elem.getAttribute(name); - - if (typeof data === "string") { - try { - data = data === "true" ? true : - data === "false" ? false : - data === "null" ? null : - jQuery.isNumeric(data) ? parseFloat(data) : - rbrace.test(data) ? jQuery.parseJSON(data) : - data; - } catch (e) { } - - // Make sure we set the data so it isn't changed later - jQuery.data(elem, key, data); - - } else { - data = undefined; - } - } - - return data; - } - - // checks a cache object for emptiness - function isEmptyDataObject(obj) { - for (var name in obj) { - - // if the public data object is empty, the private is still empty - if (name === "data" && jQuery.isEmptyObject(obj[name])) { - continue; - } - if (name !== "toJSON") { - return false; - } - } - - return true; - } - - - - - function handleQueueMarkDefer(elem, type, src) { - var deferDataKey = type + "defer", - queueDataKey = type + "queue", - markDataKey = type + "mark", - defer = jQuery._data(elem, deferDataKey); - if (defer && - (src === "queue" || !jQuery._data(elem, queueDataKey)) && - (src === "mark" || !jQuery._data(elem, markDataKey))) { - // Give room for hard-coded callbacks to fire first - // and eventually mark/queue something else on the element - setTimeout(function () { - if (!jQuery._data(elem, queueDataKey) && - !jQuery._data(elem, markDataKey)) { - jQuery.removeData(elem, deferDataKey, true); - defer.fire(); - } - }, 0); - } - } - - jQuery.extend({ - - _mark: function (elem, type) { - if (elem) { - type = (type || "fx") + "mark"; - jQuery._data(elem, type, (jQuery._data(elem, type) || 0) + 1); - } - }, - - _unmark: function (force, elem, type) { - if (force !== true) { - type = elem; - elem = force; - force = false; - } - if (elem) { - type = type || "fx"; - var key = type + "mark", - count = force ? 0 : ((jQuery._data(elem, key) || 1) - 1); - if (count) { - jQuery._data(elem, key, count); - } else { - jQuery.removeData(elem, key, true); - handleQueueMarkDefer(elem, type, "mark"); - } - } - }, - - queue: function (elem, type, data) { - var q; - if (elem) { - type = (type || "fx") + "queue"; - q = jQuery._data(elem, type); - - // Speed up dequeue by getting out quickly if this is just a lookup - if (data) { - if (!q || jQuery.isArray(data)) { - q = jQuery._data(elem, type, jQuery.makeArray(data)); - } else { - q.push(data); - } - } - return q || []; - } - }, - - dequeue: function (elem, type) { - type = type || "fx"; - - var queue = jQuery.queue(elem, type), - fn = queue.shift(), - hooks = {}; - - // If the fx queue is dequeued, always remove the progress sentinel - if (fn === "inprogress") { - fn = queue.shift(); - } - - if (fn) { - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if (type === "fx") { - queue.unshift("inprogress"); - } - - jQuery._data(elem, type + ".run", hooks); - fn.call(elem, function () { - jQuery.dequeue(elem, type); - }, hooks); - } - - if (!queue.length) { - jQuery.removeData(elem, type + "queue " + type + ".run", true); - handleQueueMarkDefer(elem, type, "queue"); - } - } - }); - - jQuery.fn.extend({ - queue: function (type, data) { - if (typeof type !== "string") { - data = type; - type = "fx"; - } - - if (data === undefined) { - return jQuery.queue(this[0], type); - } - return this.each(function () { - var queue = jQuery.queue(this, type, data); - - if (type === "fx" && queue[0] !== "inprogress") { - jQuery.dequeue(this, type); - } - }); - }, - dequeue: function (type) { - return this.each(function () { - jQuery.dequeue(this, type); - }); - }, - // Based off of the plugin by Clint Helfers, with permission. - // http://blindsignals.com/index.php/2009/07/jquery-delay/ - delay: function (time, type) { - time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; - type = type || "fx"; - - return this.queue(type, function (next, hooks) { - var timeout = setTimeout(next, time); - hooks.stop = function () { - clearTimeout(timeout); - }; - }); - }, - clearQueue: function (type) { - return this.queue(type || "fx", []); - }, - // Get a promise resolved when queues of a certain type - // are emptied (fx is the type by default) - promise: function (type, object) { - if (typeof type !== "string") { - object = type; - type = undefined; - } - type = type || "fx"; - var defer = jQuery.Deferred(), - elements = this, - i = elements.length, - count = 1, - deferDataKey = type + "defer", - queueDataKey = type + "queue", - markDataKey = type + "mark", - tmp; - function resolve() { - if (!(--count)) { - defer.resolveWith(elements, [elements]); - } - } - while (i--) { - if ((tmp = jQuery.data(elements[i], deferDataKey, undefined, true) || - (jQuery.data(elements[i], queueDataKey, undefined, true) || - jQuery.data(elements[i], markDataKey, undefined, true)) && - jQuery.data(elements[i], deferDataKey, jQuery.Callbacks("once memory"), true))) { - count++; - tmp.add(resolve); - } - } - resolve(); - return defer.promise(); - } - }); - - - - - var rclass = /[\n\t\r]/g, - rspace = /\s+/, - rreturn = /\r/g, - rtype = /^(?:button|input)$/i, - rfocusable = /^(?:button|input|object|select|textarea)$/i, - rclickable = /^a(?:rea)?$/i, - rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, - getSetAttribute = jQuery.support.getSetAttribute, - nodeHook, boolHook, fixSpecified; - - jQuery.fn.extend({ - attr: function (name, value) { - return jQuery.access(this, name, value, true, jQuery.attr); - }, - - removeAttr: function (name) { - return this.each(function () { - jQuery.removeAttr(this, name); - }); - }, - - prop: function (name, value) { - return jQuery.access(this, name, value, true, jQuery.prop); - }, - - removeProp: function (name) { - name = jQuery.propFix[name] || name; - return this.each(function () { - // try/catch handles cases where IE balks (such as removing a property on window) - try { - this[name] = undefined; - delete this[name]; - } catch (e) { } - }); - }, - - addClass: function (value) { - var classNames, i, l, elem, - setClass, c, cl; - - if (jQuery.isFunction(value)) { - return this.each(function (j) { - jQuery(this).addClass(value.call(this, j, this.className)); - }); - } - - if (value && typeof value === "string") { - classNames = value.split(rspace); - - for (i = 0, l = this.length; i < l; i++) { - elem = this[i]; - - if (elem.nodeType === 1) { - if (!elem.className && classNames.length === 1) { - elem.className = value; - - } else { - setClass = " " + elem.className + " "; - - for (c = 0, cl = classNames.length; c < cl; c++) { - if (! ~setClass.indexOf(" " + classNames[c] + " ")) { - setClass += classNames[c] + " "; - } - } - elem.className = jQuery.trim(setClass); - } - } - } - } - - return this; - }, - - removeClass: function (value) { - var classNames, i, l, elem, className, c, cl; - - if (jQuery.isFunction(value)) { - return this.each(function (j) { - jQuery(this).removeClass(value.call(this, j, this.className)); - }); - } - - if ((value && typeof value === "string") || value === undefined) { - classNames = (value || "").split(rspace); - - for (i = 0, l = this.length; i < l; i++) { - elem = this[i]; - - if (elem.nodeType === 1 && elem.className) { - if (value) { - className = (" " + elem.className + " ").replace(rclass, " "); - for (c = 0, cl = classNames.length; c < cl; c++) { - className = className.replace(" " + classNames[c] + " ", " "); - } - elem.className = jQuery.trim(className); - - } else { - elem.className = ""; - } - } - } - } - - return this; - }, - - toggleClass: function (value, stateVal) { - var type = typeof value, - isBool = typeof stateVal === "boolean"; - - if (jQuery.isFunction(value)) { - return this.each(function (i) { - jQuery(this).toggleClass(value.call(this, i, this.className, stateVal), stateVal); - }); - } - - return this.each(function () { - if (type === "string") { - // toggle individual class names - var className, - i = 0, - self = jQuery(this), - state = stateVal, - classNames = value.split(rspace); - - while ((className = classNames[i++])) { - // check each className given, space seperated list - state = isBool ? state : !self.hasClass(className); - self[state ? "addClass" : "removeClass"](className); - } - - } else if (type === "undefined" || type === "boolean") { - if (this.className) { - // store className if set - jQuery._data(this, "__className__", this.className); - } - - // toggle whole className - this.className = this.className || value === false ? "" : jQuery._data(this, "__className__") || ""; - } - }); - }, - - hasClass: function (selector) { - var className = " " + selector + " ", - i = 0, - l = this.length; - for (; i < l; i++) { - if (this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf(className) > -1) { - return true; - } - } - - return false; - }, - - val: function (value) { - var hooks, ret, isFunction, - elem = this[0]; - - if (!arguments.length) { - if (elem) { - hooks = jQuery.valHooks[elem.nodeName.toLowerCase()] || jQuery.valHooks[elem.type]; - - if (hooks && "get" in hooks && (ret = hooks.get(elem, "value")) !== undefined) { - return ret; - } - - ret = elem.value; - - return typeof ret === "string" ? - // handle most common string cases - ret.replace(rreturn, "") : - // handle cases where value is null/undef or number - ret == null ? "" : ret; - } - - return; - } - - isFunction = jQuery.isFunction(value); - - return this.each(function (i) { - var self = jQuery(this), val; - - if (this.nodeType !== 1) { - return; - } - - if (isFunction) { - val = value.call(this, i, self.val()); - } else { - val = value; - } - - // Treat null/undefined as ""; convert numbers to string - if (val == null) { - val = ""; - } else if (typeof val === "number") { - val += ""; - } else if (jQuery.isArray(val)) { - val = jQuery.map(val, function (value) { - return value == null ? "" : value + ""; - }); - } - - hooks = jQuery.valHooks[this.nodeName.toLowerCase()] || jQuery.valHooks[this.type]; - - // If set returns undefined, fall back to normal setting - if (!hooks || !("set" in hooks) || hooks.set(this, val, "value") === undefined) { - this.value = val; - } - }); - } - }); - - jQuery.extend({ - valHooks: { - option: { - get: function (elem) { - // attributes.value is undefined in Blackberry 4.7 but - // uses .value. See #6932 - var val = elem.attributes.value; - return !val || val.specified ? elem.value : elem.text; - } - }, - select: { - get: function (elem) { - var value, i, max, option, - index = elem.selectedIndex, - values = [], - options = elem.options, - one = elem.type === "select-one"; - - // Nothing was selected - if (index < 0) { - return null; - } - - // Loop through all the selected options - i = one ? index : 0; - max = one ? index + 1 : options.length; - for (; i < max; i++) { - option = options[i]; - - // Don't return options that are disabled or in a disabled optgroup - if (option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && - (!option.parentNode.disabled || !jQuery.nodeName(option.parentNode, "optgroup"))) { - - // Get the specific value for the option - value = jQuery(option).val(); - - // We don't need an array for one selects - if (one) { - return value; - } - - // Multi-Selects return an array - values.push(value); - } - } - - // Fixes Bug #2551 -- select.val() broken in IE after form.reset() - if (one && !values.length && options.length) { - return jQuery(options[index]).val(); - } - - return values; - }, - - set: function (elem, value) { - var values = jQuery.makeArray(value); - - jQuery(elem).find("option").each(function () { - this.selected = jQuery.inArray(jQuery(this).val(), values) >= 0; - }); - - if (!values.length) { - elem.selectedIndex = -1; - } - return values; - } - } - }, - - attrFn: { - val: true, - css: true, - html: true, - text: true, - data: true, - width: true, - height: true, - offset: true - }, - - attr: function (elem, name, value, pass) { - var ret, hooks, notxml, - nType = elem.nodeType; - - // don't get/set attributes on text, comment and attribute nodes - if (!elem || nType === 3 || nType === 8 || nType === 2) { - return; - } - - if (pass && name in jQuery.attrFn) { - return jQuery(elem)[name](value); - } - - // Fallback to prop when attributes are not supported - if (typeof elem.getAttribute === "undefined") { - return jQuery.prop(elem, name, value); - } - - notxml = nType !== 1 || !jQuery.isXMLDoc(elem); - - // All attributes are lowercase - // Grab necessary hook if one is defined - if (notxml) { - name = name.toLowerCase(); - hooks = jQuery.attrHooks[name] || (rboolean.test(name) ? boolHook : nodeHook); - } - - if (value !== undefined) { - - if (value === null) { - jQuery.removeAttr(elem, name); - return; - - } else if (hooks && "set" in hooks && notxml && (ret = hooks.set(elem, value, name)) !== undefined) { - return ret; - - } else { - elem.setAttribute(name, "" + value); - return value; - } - - } else if (hooks && "get" in hooks && notxml && (ret = hooks.get(elem, name)) !== null) { - return ret; - - } else { - - ret = elem.getAttribute(name); - - // Non-existent attributes return null, we normalize to undefined - return ret === null ? - undefined : - ret; - } - }, - - removeAttr: function (elem, value) { - var propName, attrNames, name, l, - i = 0; - - if (value && elem.nodeType === 1) { - attrNames = value.toLowerCase().split(rspace); - l = attrNames.length; - - for (; i < l; i++) { - name = attrNames[i]; - - if (name) { - propName = jQuery.propFix[name] || name; - - // See #9699 for explanation of this approach (setting first, then removal) - jQuery.attr(elem, name, ""); - elem.removeAttribute(getSetAttribute ? name : propName); - - // Set corresponding property to false for boolean attributes - if (rboolean.test(name) && propName in elem) { - elem[propName] = false; - } - } - } - } - }, - - attrHooks: { - type: { - set: function (elem, value) { - // We can't allow the type property to be changed (since it causes problems in IE) - if (rtype.test(elem.nodeName) && elem.parentNode) { - jQuery.error("type property can't be changed"); - } else if (!jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input")) { - // Setting the type on a radio button after the value resets the value in IE6-9 - // Reset value to it's default in case type is set after value - // This is for element creation - var val = elem.value; - elem.setAttribute("type", value); - if (val) { - elem.value = val; - } - return value; - } - } - }, - // Use the value property for back compat - // Use the nodeHook for button elements in IE6/7 (#1954) - value: { - get: function (elem, name) { - if (nodeHook && jQuery.nodeName(elem, "button")) { - return nodeHook.get(elem, name); - } - return name in elem ? - elem.value : - null; - }, - set: function (elem, value, name) { - if (nodeHook && jQuery.nodeName(elem, "button")) { - return nodeHook.set(elem, value, name); - } - // Does not return so that setAttribute is also used - elem.value = value; - } - } - }, - - propFix: { - tabindex: "tabIndex", - readonly: "readOnly", - "for": "htmlFor", - "class": "className", - maxlength: "maxLength", - cellspacing: "cellSpacing", - cellpadding: "cellPadding", - rowspan: "rowSpan", - colspan: "colSpan", - usemap: "useMap", - frameborder: "frameBorder", - contenteditable: "contentEditable" - }, - - prop: function (elem, name, value) { - var ret, hooks, notxml, - nType = elem.nodeType; - - // don't get/set properties on text, comment and attribute nodes - if (!elem || nType === 3 || nType === 8 || nType === 2) { - return; - } - - notxml = nType !== 1 || !jQuery.isXMLDoc(elem); - - if (notxml) { - // Fix name and attach hooks - name = jQuery.propFix[name] || name; - hooks = jQuery.propHooks[name]; - } - - if (value !== undefined) { - if (hooks && "set" in hooks && (ret = hooks.set(elem, value, name)) !== undefined) { - return ret; - - } else { - return (elem[name] = value); - } - - } else { - if (hooks && "get" in hooks && (ret = hooks.get(elem, name)) !== null) { - return ret; - - } else { - return elem[name]; - } - } - }, - - propHooks: { - tabIndex: { - get: function (elem) { - // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set - // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ - var attributeNode = elem.getAttributeNode("tabindex"); - - return attributeNode && attributeNode.specified ? - parseInt(attributeNode.value, 10) : - rfocusable.test(elem.nodeName) || rclickable.test(elem.nodeName) && elem.href ? - 0 : - undefined; - } - } - } - }); - - // Add the tabIndex propHook to attrHooks for back-compat (different case is intentional) - jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex; - - // Hook for boolean attributes - boolHook = { - get: function (elem, name) { - // Align boolean attributes with corresponding properties - // Fall back to attribute presence where some booleans are not supported - var attrNode, - property = jQuery.prop(elem, name); - return property === true || typeof property !== "boolean" && (attrNode = elem.getAttributeNode(name)) && attrNode.nodeValue !== false ? - name.toLowerCase() : - undefined; - }, - set: function (elem, value, name) { - var propName; - if (value === false) { - // Remove boolean attributes when set to false - jQuery.removeAttr(elem, name); - } else { - // value is true since we know at this point it's type boolean and not false - // Set boolean attributes to the same name and set the DOM property - propName = jQuery.propFix[name] || name; - if (propName in elem) { - // Only set the IDL specifically if it already exists on the element - elem[propName] = true; - } - - elem.setAttribute(name, name.toLowerCase()); - } - return name; - } - }; - - // IE6/7 do not support getting/setting some attributes with get/setAttribute - if (!getSetAttribute) { - - fixSpecified = { - name: true, - id: true - }; - - // Use this for any attribute in IE6/7 - // This fixes almost every IE6/7 issue - nodeHook = jQuery.valHooks.button = { - get: function (elem, name) { - var ret; - ret = elem.getAttributeNode(name); - return ret && (fixSpecified[name] ? ret.nodeValue !== "" : ret.specified) ? - ret.nodeValue : - undefined; - }, - set: function (elem, value, name) { - // Set the existing or create a new attribute node - var ret = elem.getAttributeNode(name); - if (!ret) { - ret = document.createAttribute(name); - elem.setAttributeNode(ret); - } - return (ret.nodeValue = value + ""); - } - }; - - // Apply the nodeHook to tabindex - jQuery.attrHooks.tabindex.set = nodeHook.set; - - // Set width and height to auto instead of 0 on empty string( Bug #8150 ) - // This is for removals - jQuery.each(["width", "height"], function (i, name) { - jQuery.attrHooks[name] = jQuery.extend(jQuery.attrHooks[name], { - set: function (elem, value) { - if (value === "") { - elem.setAttribute(name, "auto"); - return value; - } - } - }); - }); - - // Set contenteditable to false on removals(#10429) - // Setting to empty string throws an error as an invalid value - jQuery.attrHooks.contenteditable = { - get: nodeHook.get, - set: function (elem, value, name) { - if (value === "") { - value = "false"; - } - nodeHook.set(elem, value, name); - } - }; - } - - - // Some attributes require a special call on IE - if (!jQuery.support.hrefNormalized) { - jQuery.each(["href", "src", "width", "height"], function (i, name) { - jQuery.attrHooks[name] = jQuery.extend(jQuery.attrHooks[name], { - get: function (elem) { - var ret = elem.getAttribute(name, 2); - return ret === null ? undefined : ret; - } - }); - }); - } - - if (!jQuery.support.style) { - jQuery.attrHooks.style = { - get: function (elem) { - // Return undefined in the case of empty string - // Normalize to lowercase since IE uppercases css property names - return elem.style.cssText.toLowerCase() || undefined; - }, - set: function (elem, value) { - return (elem.style.cssText = "" + value); - } - }; - } - - // Safari mis-reports the default selected property of an option - // Accessing the parent's selectedIndex property fixes it - if (!jQuery.support.optSelected) { - jQuery.propHooks.selected = jQuery.extend(jQuery.propHooks.selected, { - get: function (elem) { - var parent = elem.parentNode; - - if (parent) { - parent.selectedIndex; - - // Make sure that it also works with optgroups, see #5701 - if (parent.parentNode) { - parent.parentNode.selectedIndex; - } - } - return null; - } - }); - } - - // IE6/7 call enctype encoding - if (!jQuery.support.enctype) { - jQuery.propFix.enctype = "encoding"; - } - - // Radios and checkboxes getter/setter - if (!jQuery.support.checkOn) { - jQuery.each(["radio", "checkbox"], function () { - jQuery.valHooks[this] = { - get: function (elem) { - // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified - return elem.getAttribute("value") === null ? "on" : elem.value; - } - }; - }); - } - jQuery.each(["radio", "checkbox"], function () { - jQuery.valHooks[this] = jQuery.extend(jQuery.valHooks[this], { - set: function (elem, value) { - if (jQuery.isArray(value)) { - return (elem.checked = jQuery.inArray(jQuery(elem).val(), value) >= 0); - } - } - }); - }); - - - - - var rformElems = /^(?:textarea|input|select)$/i, - rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/, - rhoverHack = /\bhover(\.\S+)?\b/, - rkeyEvent = /^key/, - rmouseEvent = /^(?:mouse|contextmenu)|click/, - rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, - rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, - quickParse = function (selector) { - var quick = rquickIs.exec(selector); - if (quick) { - // 0 1 2 3 - // [ _, tag, id, class ] - quick[1] = (quick[1] || "").toLowerCase(); - quick[3] = quick[3] && new RegExp("(?:^|\\s)" + quick[3] + "(?:\\s|$)"); - } - return quick; - }, - quickIs = function (elem, m) { - var attrs = elem.attributes || {}; - return ( - (!m[1] || elem.nodeName.toLowerCase() === m[1]) && - (!m[2] || (attrs.id || {}).value === m[2]) && - (!m[3] || m[3].test((attrs["class"] || {}).value)) - ); - }, - hoverHack = function (events) { - return jQuery.event.special.hover ? events : events.replace(rhoverHack, "mouseenter$1 mouseleave$1"); - }; - - /* - * Helper functions for managing events -- not part of the public interface. - * Props to Dean Edwards' addEvent library for many of the ideas. - */ - jQuery.event = { - - add: function (elem, types, handler, data, selector) { - - var elemData, eventHandle, events, - t, tns, type, namespaces, handleObj, - handleObjIn, quick, handlers, special; - - // Don't attach events to noData or text/comment nodes (allow plain objects tho) - if (elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data(elem))) { - return; - } - - // Caller can pass in an object of custom data in lieu of the handler - if (handler.handler) { - handleObjIn = handler; - handler = handleObjIn.handler; - } - - // Make sure that the handler has a unique ID, used to find/remove it later - if (!handler.guid) { - handler.guid = jQuery.guid++; - } - - // Init the element's event structure and main handler, if this is the first - events = elemData.events; - if (!events) { - elemData.events = events = {}; - } - eventHandle = elemData.handle; - if (!eventHandle) { - elemData.handle = eventHandle = function (e) { - // Discard the second event of a jQuery.event.trigger() and - // when an event is called after a page has unloaded - return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? - jQuery.event.dispatch.apply(eventHandle.elem, arguments) : - undefined; - }; - // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events - eventHandle.elem = elem; - } - - // Handle multiple events separated by a space - // jQuery(...).bind("mouseover mouseout", fn); - types = jQuery.trim(hoverHack(types)).split(" "); - for (t = 0; t < types.length; t++) { - - tns = rtypenamespace.exec(types[t]) || []; - type = tns[1]; - namespaces = (tns[2] || "").split(".").sort(); - - // If event changes its type, use the special event handlers for the changed type - special = jQuery.event.special[type] || {}; - - // If selector defined, determine special event api type, otherwise given type - type = (selector ? special.delegateType : special.bindType) || type; - - // Update special based on newly reset type - special = jQuery.event.special[type] || {}; - - // handleObj is passed to all event handlers - handleObj = jQuery.extend({ - type: type, - origType: tns[1], - data: data, - handler: handler, - guid: handler.guid, - selector: selector, - quick: quickParse(selector), - namespace: namespaces.join(".") - }, handleObjIn); - - // Init the event handler queue if we're the first - handlers = events[type]; - if (!handlers) { - handlers = events[type] = []; - handlers.delegateCount = 0; - - // Only use addEventListener/attachEvent if the special events handler returns false - if (!special.setup || special.setup.call(elem, data, namespaces, eventHandle) === false) { - // Bind the global event handler to the element - if (elem.addEventListener) { - elem.addEventListener(type, eventHandle, false); - - } else if (elem.attachEvent) { - elem.attachEvent("on" + type, eventHandle); - } - } - } - - if (special.add) { - special.add.call(elem, handleObj); - - if (!handleObj.handler.guid) { - handleObj.handler.guid = handler.guid; - } - } - - // Add to the element's handler list, delegates in front - if (selector) { - handlers.splice(handlers.delegateCount++, 0, handleObj); - } else { - handlers.push(handleObj); - } - - // Keep track of which events have ever been used, for event optimization - jQuery.event.global[type] = true; - } - - // Nullify elem to prevent memory leaks in IE - elem = null; - }, - - global: {}, - - // Detach an event or set of events from an element - remove: function (elem, types, handler, selector, mappedTypes) { - - var elemData = jQuery.hasData(elem) && jQuery._data(elem), - t, tns, type, origType, namespaces, origCount, - j, events, special, handle, eventType, handleObj; - - if (!elemData || !(events = elemData.events)) { - return; - } - - // Once for each type.namespace in types; type may be omitted - types = jQuery.trim(hoverHack(types || "")).split(" "); - for (t = 0; t < types.length; t++) { - tns = rtypenamespace.exec(types[t]) || []; - type = origType = tns[1]; - namespaces = tns[2]; - - // Unbind all events (on this namespace, if provided) for the element - if (!type) { - for (type in events) { - jQuery.event.remove(elem, type + types[t], handler, selector, true); - } - continue; - } - - special = jQuery.event.special[type] || {}; - type = (selector ? special.delegateType : special.bindType) || type; - eventType = events[type] || []; - origCount = eventType.length; - namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null; - - // Remove matching events - for (j = 0; j < eventType.length; j++) { - handleObj = eventType[j]; - - if ((mappedTypes || origType === handleObj.origType) && - (!handler || handler.guid === handleObj.guid) && - (!namespaces || namespaces.test(handleObj.namespace)) && - (!selector || selector === handleObj.selector || selector === "**" && handleObj.selector)) { - eventType.splice(j--, 1); - - if (handleObj.selector) { - eventType.delegateCount--; - } - if (special.remove) { - special.remove.call(elem, handleObj); - } - } - } - - // Remove generic event handler if we removed something and no more handlers exist - // (avoids potential for endless recursion during removal of special event handlers) - if (eventType.length === 0 && origCount !== eventType.length) { - if (!special.teardown || special.teardown.call(elem, namespaces) === false) { - jQuery.removeEvent(elem, type, elemData.handle); - } - - delete events[type]; - } - } - - // Remove the expando if it's no longer used - if (jQuery.isEmptyObject(events)) { - handle = elemData.handle; - if (handle) { - handle.elem = null; - } - - // removeData also checks for emptiness and clears the expando if empty - // so use it instead of delete - jQuery.removeData(elem, ["events", "handle"], true); - } - }, - - // Events that are safe to short-circuit if no handlers are attached. - // Native DOM events should not be added, they may have inline handlers. - customEvent: { - "getData": true, - "setData": true, - "changeData": true - }, - - trigger: function (event, data, elem, onlyHandlers) { - // Don't do events on text and comment nodes - if (elem && (elem.nodeType === 3 || elem.nodeType === 8)) { - return; - } - - // Event object or event type - var type = event.type || event, - namespaces = [], - cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType; - - // focus/blur morphs to focusin/out; ensure we're not firing them right now - if (rfocusMorph.test(type + jQuery.event.triggered)) { - return; - } - - if (type.indexOf("!") >= 0) { - // Exclusive events trigger only for the exact event (no namespaces) - type = type.slice(0, -1); - exclusive = true; - } - - if (type.indexOf(".") >= 0) { - // Namespaced trigger; create a regexp to match event type in handle() - namespaces = type.split("."); - type = namespaces.shift(); - namespaces.sort(); - } - - if ((!elem || jQuery.event.customEvent[type]) && !jQuery.event.global[type]) { - // No jQuery handlers for this event type, and it can't have inline handlers - return; - } - - // Caller can pass in an Event, Object, or just an event type string - event = typeof event === "object" ? - // jQuery.Event object - event[jQuery.expando] ? event : - // Object literal - new jQuery.Event(type, event) : - // Just the event type (string) - new jQuery.Event(type); - - event.type = type; - event.isTrigger = true; - event.exclusive = exclusive; - event.namespace = namespaces.join("."); - event.namespace_re = event.namespace ? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null; - ontype = type.indexOf(":") < 0 ? "on" + type : ""; - - // Handle a global trigger - if (!elem) { - - // TODO: Stop taunting the data cache; remove global events and always attach to document - cache = jQuery.cache; - for (i in cache) { - if (cache[i].events && cache[i].events[type]) { - jQuery.event.trigger(event, data, cache[i].handle.elem, true); - } - } - return; - } - - // Clean up the event in case it is being reused - event.result = undefined; - if (!event.target) { - event.target = elem; - } - - // Clone any incoming data and prepend the event, creating the handler arg list - data = data != null ? jQuery.makeArray(data) : []; - data.unshift(event); - - // Allow special events to draw outside the lines - special = jQuery.event.special[type] || {}; - if (special.trigger && special.trigger.apply(elem, data) === false) { - return; - } - - // Determine event propagation path in advance, per W3C events spec (#9951) - // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) - eventPath = [[elem, special.bindType || type]]; - if (!onlyHandlers && !special.noBubble && !jQuery.isWindow(elem)) { - - bubbleType = special.delegateType || type; - cur = rfocusMorph.test(bubbleType + type) ? elem : elem.parentNode; - old = null; - for (; cur; cur = cur.parentNode) { - eventPath.push([cur, bubbleType]); - old = cur; - } - - // Only add window if we got to document (e.g., not plain obj or detached DOM) - if (old && old === elem.ownerDocument) { - eventPath.push([old.defaultView || old.parentWindow || window, bubbleType]); - } - } - - // Fire handlers on the event path - for (i = 0; i < eventPath.length && !event.isPropagationStopped(); i++) { - - cur = eventPath[i][0]; - event.type = eventPath[i][1]; - - handle = (jQuery._data(cur, "events") || {})[event.type] && jQuery._data(cur, "handle"); - if (handle) { - handle.apply(cur, data); - } - // Note that this is a bare JS function and not a jQuery handler - handle = ontype && cur[ontype]; - if (handle && jQuery.acceptData(cur) && handle.apply(cur, data) === false) { - event.preventDefault(); - } - } - event.type = type; - - // If nobody prevented the default action, do it now - if (!onlyHandlers && !event.isDefaultPrevented()) { - - if ((!special._default || special._default.apply(elem.ownerDocument, data) === false) && - !(type === "click" && jQuery.nodeName(elem, "a")) && jQuery.acceptData(elem)) { - - // Call a native DOM method on the target with the same name name as the event. - // Can't use an .isFunction() check here because IE6/7 fails that test. - // Don't do default actions on window, that's where global variables be (#6170) - // IE<9 dies on focus/blur to hidden element (#1486) - if (ontype && elem[type] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow(elem)) { - - // Don't re-trigger an onFOO event when we call its FOO() method - old = elem[ontype]; - - if (old) { - elem[ontype] = null; - } - - // Prevent re-triggering of the same event, since we already bubbled it above - jQuery.event.triggered = type; - elem[type](); - jQuery.event.triggered = undefined; - - if (old) { - elem[ontype] = old; - } - } - } - } - - return event.result; - }, - - dispatch: function (event) { - - // Make a writable jQuery.Event from the native event object - event = jQuery.event.fix(event || window.event); - - var handlers = ((jQuery._data(this, "events") || {})[event.type] || []), - delegateCount = handlers.delegateCount, - args = [].slice.call(arguments, 0), - run_all = !event.exclusive && !event.namespace, - handlerQueue = [], - i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related; - - // Use the fix-ed jQuery.Event rather than the (read-only) native event - args[0] = event; - event.delegateTarget = this; - - // Determine handlers that should run if there are delegated events - // Avoid disabled elements in IE (#6911) and non-left-click bubbling in Firefox (#3861) - if (delegateCount && !event.target.disabled && !(event.button && event.type === "click")) { - - // Pregenerate a single jQuery object for reuse with .is() - jqcur = jQuery(this); - jqcur.context = this.ownerDocument || this; - - for (cur = event.target; cur != this; cur = cur.parentNode || this) { - selMatch = {}; - matches = []; - jqcur[0] = cur; - for (i = 0; i < delegateCount; i++) { - handleObj = handlers[i]; - sel = handleObj.selector; - - if (selMatch[sel] === undefined) { - selMatch[sel] = ( - handleObj.quick ? quickIs(cur, handleObj.quick) : jqcur.is(sel) - ); - } - if (selMatch[sel]) { - matches.push(handleObj); - } - } - if (matches.length) { - handlerQueue.push({ elem: cur, matches: matches }); - } - } - } - - // Add the remaining (directly-bound) handlers - if (handlers.length > delegateCount) { - handlerQueue.push({ elem: this, matches: handlers.slice(delegateCount) }); - } - - // Run delegates first; they may want to stop propagation beneath us - for (i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++) { - matched = handlerQueue[i]; - event.currentTarget = matched.elem; - - for (j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++) { - handleObj = matched.matches[j]; - - // Triggered event must either 1) be non-exclusive and have no namespace, or - // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). - if (run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test(handleObj.namespace)) { - - event.data = handleObj.data; - event.handleObj = handleObj; - - ret = ((jQuery.event.special[handleObj.origType] || {}).handle || handleObj.handler) - .apply(matched.elem, args); - - if (ret !== undefined) { - event.result = ret; - if (ret === false) { - event.preventDefault(); - event.stopPropagation(); - } - } - } - } - } - - return event.result; - }, - - // Includes some event props shared by KeyEvent and MouseEvent - // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** - props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), - - fixHooks: {}, - - keyHooks: { - props: "char charCode key keyCode".split(" "), - filter: function (event, original) { - - // Add which for key events - if (event.which == null) { - event.which = original.charCode != null ? original.charCode : original.keyCode; - } - - return event; - } - }, - - mouseHooks: { - props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), - filter: function (event, original) { - var eventDoc, doc, body, - button = original.button, - fromElement = original.fromElement; - - // Calculate pageX/Y if missing and clientX/Y available - if (event.pageX == null && original.clientX != null) { - eventDoc = event.target.ownerDocument || document; - doc = eventDoc.documentElement; - body = eventDoc.body; - - event.pageX = original.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); - event.pageY = original.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); - } - - // Add relatedTarget, if necessary - if (!event.relatedTarget && fromElement) { - event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; - } - - // Add which for click: 1 === left; 2 === middle; 3 === right - // Note: button is not normalized, so don't use it - if (!event.which && button !== undefined) { - event.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0))); - } - - return event; - } - }, - - fix: function (event) { - if (event[jQuery.expando]) { - return event; - } - - // Create a writable copy of the event object and normalize some properties - var i, prop, - originalEvent = event, - fixHook = jQuery.event.fixHooks[event.type] || {}, - copy = fixHook.props ? this.props.concat(fixHook.props) : this.props; - - event = jQuery.Event(originalEvent); - - for (i = copy.length; i; ) { - prop = copy[--i]; - event[prop] = originalEvent[prop]; - } - - // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) - if (!event.target) { - event.target = originalEvent.srcElement || document; - } - - // Target should not be a text node (#504, Safari) - if (event.target.nodeType === 3) { - event.target = event.target.parentNode; - } - - // For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8) - if (event.metaKey === undefined) { - event.metaKey = event.ctrlKey; - } - - return fixHook.filter ? fixHook.filter(event, originalEvent) : event; - }, - - special: { - ready: { - // Make sure the ready event is setup - setup: jQuery.bindReady - }, - - load: { - // Prevent triggered image.load events from bubbling to window.load - noBubble: true - }, - - focus: { - delegateType: "focusin" - }, - blur: { - delegateType: "focusout" - }, - - beforeunload: { - setup: function (data, namespaces, eventHandle) { - // We only want to do this special case on windows - if (jQuery.isWindow(this)) { - this.onbeforeunload = eventHandle; - } - }, - - teardown: function (namespaces, eventHandle) { - if (this.onbeforeunload === eventHandle) { - this.onbeforeunload = null; - } - } - } - }, - - simulate: function (type, elem, event, bubble) { - // Piggyback on a donor event to simulate a different one. - // Fake originalEvent to avoid donor's stopPropagation, but if the - // simulated event prevents default then we do the same on the donor. - var e = jQuery.extend( - new jQuery.Event(), - event, - { type: type, - isSimulated: true, - originalEvent: {} - } - ); - if (bubble) { - jQuery.event.trigger(e, null, elem); - } else { - jQuery.event.dispatch.call(elem, e); - } - if (e.isDefaultPrevented()) { - event.preventDefault(); - } - } - }; - - // Some plugins are using, but it's undocumented/deprecated and will be removed. - // The 1.7 special event interface should provide all the hooks needed now. - jQuery.event.handle = jQuery.event.dispatch; - - jQuery.removeEvent = document.removeEventListener ? - function (elem, type, handle) { - if (elem.removeEventListener) { - elem.removeEventListener(type, handle, false); - } - } : - function (elem, type, handle) { - if (elem.detachEvent) { - elem.detachEvent("on" + type, handle); - } - }; - - jQuery.Event = function (src, props) { - // Allow instantiation without the 'new' keyword - if (!(this instanceof jQuery.Event)) { - return new jQuery.Event(src, props); - } - - // Event object - if (src && src.type) { - this.originalEvent = src; - this.type = src.type; - - // Events bubbling up the document may have been marked as prevented - // by a handler lower down the tree; reflect the correct value. - this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false || - src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse; - - // Event type - } else { - this.type = src; - } - - // Put explicitly provided properties onto the event object - if (props) { - jQuery.extend(this, props); - } - - // Create a timestamp if incoming event doesn't have one - this.timeStamp = src && src.timeStamp || jQuery.now(); - - // Mark it as fixed - this[jQuery.expando] = true; - }; - - function returnFalse() { - return false; - } - function returnTrue() { - return true; - } - - // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding - // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html - jQuery.Event.prototype = { - preventDefault: function () { - this.isDefaultPrevented = returnTrue; - - var e = this.originalEvent; - if (!e) { - return; - } - - // if preventDefault exists run it on the original event - if (e.preventDefault) { - e.preventDefault(); - - // otherwise set the returnValue property of the original event to false (IE) - } else { - e.returnValue = false; - } - }, - stopPropagation: function () { - this.isPropagationStopped = returnTrue; - - var e = this.originalEvent; - if (!e) { - return; - } - // if stopPropagation exists run it on the original event - if (e.stopPropagation) { - e.stopPropagation(); - } - // otherwise set the cancelBubble property of the original event to true (IE) - e.cancelBubble = true; - }, - stopImmediatePropagation: function () { - this.isImmediatePropagationStopped = returnTrue; - this.stopPropagation(); - }, - isDefaultPrevented: returnFalse, - isPropagationStopped: returnFalse, - isImmediatePropagationStopped: returnFalse - }; - - // Create mouseenter/leave events using mouseover/out and event-time checks - jQuery.each({ - mouseenter: "mouseover", - mouseleave: "mouseout" - }, function (orig, fix) { - jQuery.event.special[orig] = { - delegateType: fix, - bindType: fix, - - handle: function (event) { - var target = this, - related = event.relatedTarget, - handleObj = event.handleObj, - selector = handleObj.selector, - ret; - - // For mousenter/leave call the handler if related is outside the target. - // NB: No relatedTarget if the mouse left/entered the browser window - if (!related || (related !== target && !jQuery.contains(target, related))) { - event.type = handleObj.origType; - ret = handleObj.handler.apply(this, arguments); - event.type = fix; - } - return ret; - } - }; - }); - - // IE submit delegation - if (!jQuery.support.submitBubbles) { - - jQuery.event.special.submit = { - setup: function () { - // Only need this for delegated form submit events - if (jQuery.nodeName(this, "form")) { - return false; - } - - // Lazy-add a submit handler when a descendant form may potentially be submitted - jQuery.event.add(this, "click._submit keypress._submit", function (e) { - // Node name check avoids a VML-related crash in IE (#9807) - var elem = e.target, - form = jQuery.nodeName(elem, "input") || jQuery.nodeName(elem, "button") ? elem.form : undefined; - if (form && !form._submit_attached) { - jQuery.event.add(form, "submit._submit", function (event) { - // If form was submitted by the user, bubble the event up the tree - if (this.parentNode && !event.isTrigger) { - jQuery.event.simulate("submit", this.parentNode, event, true); - } - }); - form._submit_attached = true; - } - }); - // return undefined since we don't need an event listener - }, - - teardown: function () { - // Only need this for delegated form submit events - if (jQuery.nodeName(this, "form")) { - return false; - } - - // Remove delegated handlers; cleanData eventually reaps submit handlers attached above - jQuery.event.remove(this, "._submit"); - } - }; - } - - // IE change delegation and checkbox/radio fix - if (!jQuery.support.changeBubbles) { - - jQuery.event.special.change = { - - setup: function () { - - if (rformElems.test(this.nodeName)) { - // IE doesn't fire change on a check/radio until blur; trigger it on click - // after a propertychange. Eat the blur-change in special.change.handle. - // This still fires onchange a second time for check/radio after blur. - if (this.type === "checkbox" || this.type === "radio") { - jQuery.event.add(this, "propertychange._change", function (event) { - if (event.originalEvent.propertyName === "checked") { - this._just_changed = true; - } - }); - jQuery.event.add(this, "click._change", function (event) { - if (this._just_changed && !event.isTrigger) { - this._just_changed = false; - jQuery.event.simulate("change", this, event, true); - } - }); - } - return false; - } - // Delegated event; lazy-add a change handler on descendant inputs - jQuery.event.add(this, "beforeactivate._change", function (e) { - var elem = e.target; - - if (rformElems.test(elem.nodeName) && !elem._change_attached) { - jQuery.event.add(elem, "change._change", function (event) { - if (this.parentNode && !event.isSimulated && !event.isTrigger) { - jQuery.event.simulate("change", this.parentNode, event, true); - } - }); - elem._change_attached = true; - } - }); - }, - - handle: function (event) { - var elem = event.target; - - // Swallow native change events from checkbox/radio, we already triggered them above - if (this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox")) { - return event.handleObj.handler.apply(this, arguments); - } - }, - - teardown: function () { - jQuery.event.remove(this, "._change"); - - return rformElems.test(this.nodeName); - } - }; - } - - // Create "bubbling" focus and blur events - if (!jQuery.support.focusinBubbles) { - jQuery.each({ focus: "focusin", blur: "focusout" }, function (orig, fix) { - - // Attach a single capturing handler while someone wants focusin/focusout - var attaches = 0, - handler = function (event) { - jQuery.event.simulate(fix, event.target, jQuery.event.fix(event), true); - }; - - jQuery.event.special[fix] = { - setup: function () { - if (attaches++ === 0) { - document.addEventListener(orig, handler, true); - } - }, - teardown: function () { - if (--attaches === 0) { - document.removeEventListener(orig, handler, true); - } - } - }; - }); - } - - jQuery.fn.extend({ - - on: function (types, selector, data, fn, /*INTERNAL*/one) { - var origFn, type; - - // Types can be a map of types/handlers - if (typeof types === "object") { - // ( types-Object, selector, data ) - if (typeof selector !== "string") { - // ( types-Object, data ) - data = selector; - selector = undefined; - } - for (type in types) { - this.on(type, selector, data, types[type], one); - } - return this; - } - - if (data == null && fn == null) { - // ( types, fn ) - fn = selector; - data = selector = undefined; - } else if (fn == null) { - if (typeof selector === "string") { - // ( types, selector, fn ) - fn = data; - data = undefined; - } else { - // ( types, data, fn ) - fn = data; - data = selector; - selector = undefined; - } - } - if (fn === false) { - fn = returnFalse; - } else if (!fn) { - return this; - } - - if (one === 1) { - origFn = fn; - fn = function (event) { - // Can use an empty set, since event contains the info - jQuery().off(event); - return origFn.apply(this, arguments); - }; - // Use same guid so caller can remove using origFn - fn.guid = origFn.guid || (origFn.guid = jQuery.guid++); - } - return this.each(function () { - jQuery.event.add(this, types, fn, data, selector); - }); - }, - one: function (types, selector, data, fn) { - return this.on.call(this, types, selector, data, fn, 1); - }, - off: function (types, selector, fn) { - if (types && types.preventDefault && types.handleObj) { - // ( event ) dispatched jQuery.Event - var handleObj = types.handleObj; - jQuery(types.delegateTarget).off( - handleObj.namespace ? handleObj.type + "." + handleObj.namespace : handleObj.type, - handleObj.selector, - handleObj.handler - ); - return this; - } - if (typeof types === "object") { - // ( types-object [, selector] ) - for (var type in types) { - this.off(type, selector, types[type]); - } - return this; - } - if (selector === false || typeof selector === "function") { - // ( types [, fn] ) - fn = selector; - selector = undefined; - } - if (fn === false) { - fn = returnFalse; - } - return this.each(function () { - jQuery.event.remove(this, types, fn, selector); - }); - }, - - bind: function (types, data, fn) { - return this.on(types, null, data, fn); - }, - unbind: function (types, fn) { - return this.off(types, null, fn); - }, - - live: function (types, data, fn) { - jQuery(this.context).on(types, this.selector, data, fn); - return this; - }, - die: function (types, fn) { - jQuery(this.context).off(types, this.selector || "**", fn); - return this; - }, - - delegate: function (selector, types, data, fn) { - return this.on(types, selector, data, fn); - }, - undelegate: function (selector, types, fn) { - // ( namespace ) or ( selector, types [, fn] ) - return arguments.length == 1 ? this.off(selector, "**") : this.off(types, selector, fn); - }, - - trigger: function (type, data) { - return this.each(function () { - jQuery.event.trigger(type, data, this); - }); - }, - triggerHandler: function (type, data) { - if (this[0]) { - return jQuery.event.trigger(type, data, this[0], true); - } - }, - - toggle: function (fn) { - // Save reference to arguments for access in closure - var args = arguments, - guid = fn.guid || jQuery.guid++, - i = 0, - toggler = function (event) { - // Figure out which function to execute - var lastToggle = (jQuery._data(this, "lastToggle" + fn.guid) || 0) % i; - jQuery._data(this, "lastToggle" + fn.guid, lastToggle + 1); - - // Make sure that clicks stop - event.preventDefault(); - - // and execute the function - return args[lastToggle].apply(this, arguments) || false; - }; - - // link all the functions, so any of them can unbind this click handler - toggler.guid = guid; - while (i < args.length) { - args[i++].guid = guid; - } - - return this.click(toggler); - }, - - hover: function (fnOver, fnOut) { - return this.mouseenter(fnOver).mouseleave(fnOut || fnOver); - } - }); - - jQuery.each(("blur focus focusin focusout load resize scroll unload click dblclick " + - "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + - "change select submit keydown keypress keyup error contextmenu").split(" "), function (i, name) { - - // Handle event binding - jQuery.fn[name] = function (data, fn) { - if (fn == null) { - fn = data; - data = null; - } - - return arguments.length > 0 ? - this.on(name, null, data, fn) : - this.trigger(name); - }; - - if (jQuery.attrFn) { - jQuery.attrFn[name] = true; - } - - if (rkeyEvent.test(name)) { - jQuery.event.fixHooks[name] = jQuery.event.keyHooks; - } - - if (rmouseEvent.test(name)) { - jQuery.event.fixHooks[name] = jQuery.event.mouseHooks; - } - }); - - - - /*! - * Sizzle CSS Selector Engine - * Copyright 2011, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * More information: http://sizzlejs.com/ - */ - (function () { - - var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, - expando = "sizcache" + (Math.random() + '').replace('.', ''), - done = 0, - toString = Object.prototype.toString, - hasDuplicate = false, - baseHasDuplicate = true, - rBackslash = /\\/g, - rReturn = /\r\n/g, - rNonWord = /\W/; - - // Here we check if the JavaScript engine is using some sort of - // optimization where it does not always call our comparision - // function. If that is the case, discard the hasDuplicate value. - // Thus far that includes Google Chrome. - [0, 0].sort(function () { - baseHasDuplicate = false; - return 0; - }); - - var Sizzle = function (selector, context, results, seed) { - results = results || []; - context = context || document; - - var origContext = context; - - if (context.nodeType !== 1 && context.nodeType !== 9) { - return []; - } - - if (!selector || typeof selector !== "string") { - return results; - } - - var m, set, checkSet, extra, ret, cur, pop, i, - prune = true, - contextXML = Sizzle.isXML(context), - parts = [], - soFar = selector; - - // Reset the position of the chunker regexp (start from head) - do { - chunker.exec(""); - m = chunker.exec(soFar); - - if (m) { - soFar = m[3]; - - parts.push(m[1]); - - if (m[2]) { - extra = m[3]; - break; - } - } - } while (m); - - if (parts.length > 1 && origPOS.exec(selector)) { - - if (parts.length === 2 && Expr.relative[parts[0]]) { - set = posProcess(parts[0] + parts[1], context, seed); - - } else { - set = Expr.relative[parts[0]] ? - [context] : - Sizzle(parts.shift(), context); - - while (parts.length) { - selector = parts.shift(); - - if (Expr.relative[selector]) { - selector += parts.shift(); - } - - set = posProcess(selector, set, seed); - } - } - - } else { - // Take a shortcut and set the context if the root selector is an ID - // (but not if it'll be faster if the inner selector is an ID) - if (!seed && parts.length > 1 && context.nodeType === 9 && !contextXML && - Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1])) { - - ret = Sizzle.find(parts.shift(), context, contextXML); - context = ret.expr ? - Sizzle.filter(ret.expr, ret.set)[0] : - ret.set[0]; - } - - if (context) { - ret = seed ? - { expr: parts.pop(), set: makeArray(seed)} : - Sizzle.find(parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML); - - set = ret.expr ? - Sizzle.filter(ret.expr, ret.set) : - ret.set; - - if (parts.length > 0) { - checkSet = makeArray(set); - - } else { - prune = false; - } - - while (parts.length) { - cur = parts.pop(); - pop = cur; - - if (!Expr.relative[cur]) { - cur = ""; - } else { - pop = parts.pop(); - } - - if (pop == null) { - pop = context; - } - - Expr.relative[cur](checkSet, pop, contextXML); - } - - } else { - checkSet = parts = []; - } - } - - if (!checkSet) { - checkSet = set; - } - - if (!checkSet) { - Sizzle.error(cur || selector); - } - - if (toString.call(checkSet) === "[object Array]") { - if (!prune) { - results.push.apply(results, checkSet); - - } else if (context && context.nodeType === 1) { - for (i = 0; checkSet[i] != null; i++) { - if (checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i]))) { - results.push(set[i]); - } - } - - } else { - for (i = 0; checkSet[i] != null; i++) { - if (checkSet[i] && checkSet[i].nodeType === 1) { - results.push(set[i]); - } - } - } - - } else { - makeArray(checkSet, results); - } - - if (extra) { - Sizzle(extra, origContext, results, seed); - Sizzle.uniqueSort(results); - } - - return results; - }; - - Sizzle.uniqueSort = function (results) { - if (sortOrder) { - hasDuplicate = baseHasDuplicate; - results.sort(sortOrder); - - if (hasDuplicate) { - for (var i = 1; i < results.length; i++) { - if (results[i] === results[i - 1]) { - results.splice(i--, 1); - } - } - } - } - - return results; - }; - - Sizzle.matches = function (expr, set) { - return Sizzle(expr, null, null, set); - }; - - Sizzle.matchesSelector = function (node, expr) { - return Sizzle(expr, null, null, [node]).length > 0; - }; - - Sizzle.find = function (expr, context, isXML) { - var set, i, len, match, type, left; - - if (!expr) { - return []; - } - - for (i = 0, len = Expr.order.length; i < len; i++) { - type = Expr.order[i]; - - if ((match = Expr.leftMatch[type].exec(expr))) { - left = match[1]; - match.splice(1, 1); - - if (left.substr(left.length - 1) !== "\\") { - match[1] = (match[1] || "").replace(rBackslash, ""); - set = Expr.find[type](match, context, isXML); - - if (set != null) { - expr = expr.replace(Expr.match[type], ""); - break; - } - } - } - } - - if (!set) { - set = typeof context.getElementsByTagName !== "undefined" ? - context.getElementsByTagName("*") : - []; - } - - return { set: set, expr: expr }; - }; - - Sizzle.filter = function (expr, set, inplace, not) { - var match, anyFound, - type, found, item, filter, left, - i, pass, - old = expr, - result = [], - curLoop = set, - isXMLFilter = set && set[0] && Sizzle.isXML(set[0]); - - while (expr && set.length) { - for (type in Expr.filter) { - if ((match = Expr.leftMatch[type].exec(expr)) != null && match[2]) { - filter = Expr.filter[type]; - left = match[1]; - - anyFound = false; - - match.splice(1, 1); - - if (left.substr(left.length - 1) === "\\") { - continue; - } - - if (curLoop === result) { - result = []; - } - - if (Expr.preFilter[type]) { - match = Expr.preFilter[type](match, curLoop, inplace, result, not, isXMLFilter); - - if (!match) { - anyFound = found = true; - - } else if (match === true) { - continue; - } - } - - if (match) { - for (i = 0; (item = curLoop[i]) != null; i++) { - if (item) { - found = filter(item, match, i, curLoop); - pass = not ^ found; - - if (inplace && found != null) { - if (pass) { - anyFound = true; - - } else { - curLoop[i] = false; - } - - } else if (pass) { - result.push(item); - anyFound = true; - } - } - } - } - - if (found !== undefined) { - if (!inplace) { - curLoop = result; - } - - expr = expr.replace(Expr.match[type], ""); - - if (!anyFound) { - return []; - } - - break; - } - } - } - - // Improper expression - if (expr === old) { - if (anyFound == null) { - Sizzle.error(expr); - - } else { - break; - } - } - - old = expr; - } - - return curLoop; - }; - - Sizzle.error = function (msg) { - throw new Error("Syntax error, unrecognized expression: " + msg); - }; - - /** - * Utility function for retreiving the text value of an array of DOM nodes - * @param {Array|Element} elem - */ - var getText = Sizzle.getText = function (elem) { - var i, node, - nodeType = elem.nodeType, - ret = ""; - - if (nodeType) { - if (nodeType === 1 || nodeType === 9) { - // Use textContent || innerText for elements - if (typeof elem.textContent === 'string') { - return elem.textContent; - } else if (typeof elem.innerText === 'string') { - // Replace IE's carriage returns - return elem.innerText.replace(rReturn, ''); - } else { - // Traverse it's children - for (elem = elem.firstChild; elem; elem = elem.nextSibling) { - ret += getText(elem); - } - } - } else if (nodeType === 3 || nodeType === 4) { - return elem.nodeValue; - } - } else { - - // If no nodeType, this is expected to be an array - for (i = 0; (node = elem[i]); i++) { - // Do not traverse comment nodes - if (node.nodeType !== 8) { - ret += getText(node); - } - } - } - return ret; - }; - - var Expr = Sizzle.selectors = { - order: ["ID", "NAME", "TAG"], - - match: { - ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, - CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, - NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, - ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, - TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, - CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, - POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, - PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ - }, - - leftMatch: {}, - - attrMap: { - "class": "className", - "for": "htmlFor" - }, - - attrHandle: { - href: function (elem) { - return elem.getAttribute("href"); - }, - type: function (elem) { - return elem.getAttribute("type"); - } - }, - - relative: { - "+": function (checkSet, part) { - var isPartStr = typeof part === "string", - isTag = isPartStr && !rNonWord.test(part), - isPartStrNotTag = isPartStr && !isTag; - - if (isTag) { - part = part.toLowerCase(); - } - - for (var i = 0, l = checkSet.length, elem; i < l; i++) { - if ((elem = checkSet[i])) { - while ((elem = elem.previousSibling) && elem.nodeType !== 1) { } - - checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? - elem || false : - elem === part; - } - } - - if (isPartStrNotTag) { - Sizzle.filter(part, checkSet, true); - } - }, - - ">": function (checkSet, part) { - var elem, - isPartStr = typeof part === "string", - i = 0, - l = checkSet.length; - - if (isPartStr && !rNonWord.test(part)) { - part = part.toLowerCase(); - - for (; i < l; i++) { - elem = checkSet[i]; - - if (elem) { - var parent = elem.parentNode; - checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; - } - } - - } else { - for (; i < l; i++) { - elem = checkSet[i]; - - if (elem) { - checkSet[i] = isPartStr ? - elem.parentNode : - elem.parentNode === part; - } - } - - if (isPartStr) { - Sizzle.filter(part, checkSet, true); - } - } - }, - - "": function (checkSet, part, isXML) { - var nodeCheck, - doneName = done++, - checkFn = dirCheck; - - if (typeof part === "string" && !rNonWord.test(part)) { - part = part.toLowerCase(); - nodeCheck = part; - checkFn = dirNodeCheck; - } - - checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML); - }, - - "~": function (checkSet, part, isXML) { - var nodeCheck, - doneName = done++, - checkFn = dirCheck; - - if (typeof part === "string" && !rNonWord.test(part)) { - part = part.toLowerCase(); - nodeCheck = part; - checkFn = dirNodeCheck; - } - - checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML); - } - }, - - find: { - ID: function (match, context, isXML) { - if (typeof context.getElementById !== "undefined" && !isXML) { - var m = context.getElementById(match[1]); - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - return m && m.parentNode ? [m] : []; - } - }, - - NAME: function (match, context) { - if (typeof context.getElementsByName !== "undefined") { - var ret = [], - results = context.getElementsByName(match[1]); - - for (var i = 0, l = results.length; i < l; i++) { - if (results[i].getAttribute("name") === match[1]) { - ret.push(results[i]); - } - } - - return ret.length === 0 ? null : ret; - } - }, - - TAG: function (match, context) { - if (typeof context.getElementsByTagName !== "undefined") { - return context.getElementsByTagName(match[1]); - } - } - }, - preFilter: { - CLASS: function (match, curLoop, inplace, result, not, isXML) { - match = " " + match[1].replace(rBackslash, "") + " "; - - if (isXML) { - return match; - } - - for (var i = 0, elem; (elem = curLoop[i]) != null; i++) { - if (elem) { - if (not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0)) { - if (!inplace) { - result.push(elem); - } - - } else if (inplace) { - curLoop[i] = false; - } - } - } - - return false; - }, - - ID: function (match) { - return match[1].replace(rBackslash, ""); - }, - - TAG: function (match, curLoop) { - return match[1].replace(rBackslash, "").toLowerCase(); - }, - - CHILD: function (match) { - if (match[1] === "nth") { - if (!match[2]) { - Sizzle.error(match[0]); - } - - match[2] = match[2].replace(/^\+|\s*/g, ''); - - // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' - var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( - match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || - !/\D/.test(match[2]) && "0n+" + match[2] || match[2]); - - // calculate the numbers (first)n+(last) including if they are negative - match[2] = (test[1] + (test[2] || 1)) - 0; - match[3] = test[3] - 0; - } - else if (match[2]) { - Sizzle.error(match[0]); - } - - // TODO: Move to normal caching system - match[0] = done++; - - return match; - }, - - ATTR: function (match, curLoop, inplace, result, not, isXML) { - var name = match[1] = match[1].replace(rBackslash, ""); - - if (!isXML && Expr.attrMap[name]) { - match[1] = Expr.attrMap[name]; - } - - // Handle if an un-quoted value was used - match[4] = (match[4] || match[5] || "").replace(rBackslash, ""); - - if (match[2] === "~=") { - match[4] = " " + match[4] + " "; - } - - return match; - }, - - PSEUDO: function (match, curLoop, inplace, result, not) { - if (match[1] === "not") { - // If we're dealing with a complex expression, or a simple one - if ((chunker.exec(match[3]) || "").length > 1 || /^\w/.test(match[3])) { - match[3] = Sizzle(match[3], null, null, curLoop); - - } else { - var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); - - if (!inplace) { - result.push.apply(result, ret); - } - - return false; - } - - } else if (Expr.match.POS.test(match[0]) || Expr.match.CHILD.test(match[0])) { - return true; - } - - return match; - }, - - POS: function (match) { - match.unshift(true); - - return match; - } - }, - - filters: { - enabled: function (elem) { - return elem.disabled === false && elem.type !== "hidden"; - }, - - disabled: function (elem) { - return elem.disabled === true; - }, - - checked: function (elem) { - return elem.checked === true; - }, - - selected: function (elem) { - // Accessing this property makes selected-by-default - // options in Safari work properly - if (elem.parentNode) { - elem.parentNode.selectedIndex; - } - - return elem.selected === true; - }, - - parent: function (elem) { - return !!elem.firstChild; - }, - - empty: function (elem) { - return !elem.firstChild; - }, - - has: function (elem, i, match) { - return !!Sizzle(match[3], elem).length; - }, - - header: function (elem) { - return (/h\d/i).test(elem.nodeName); - }, - - text: function (elem) { - var attr = elem.getAttribute("type"), type = elem.type; - // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) - // use getAttribute instead to test this case - return elem.nodeName.toLowerCase() === "input" && "text" === type && (attr === type || attr === null); - }, - - radio: function (elem) { - return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; - }, - - checkbox: function (elem) { - return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; - }, - - file: function (elem) { - return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; - }, - - password: function (elem) { - return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; - }, - - submit: function (elem) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && "submit" === elem.type; - }, - - image: function (elem) { - return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; - }, - - reset: function (elem) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && "reset" === elem.type; - }, - - button: function (elem) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && "button" === elem.type || name === "button"; - }, - - input: function (elem) { - return (/input|select|textarea|button/i).test(elem.nodeName); - }, - - focus: function (elem) { - return elem === elem.ownerDocument.activeElement; - } - }, - setFilters: { - first: function (elem, i) { - return i === 0; - }, - - last: function (elem, i, match, array) { - return i === array.length - 1; - }, - - even: function (elem, i) { - return i % 2 === 0; - }, - - odd: function (elem, i) { - return i % 2 === 1; - }, - - lt: function (elem, i, match) { - return i < match[3] - 0; - }, - - gt: function (elem, i, match) { - return i > match[3] - 0; - }, - - nth: function (elem, i, match) { - return match[3] - 0 === i; - }, - - eq: function (elem, i, match) { - return match[3] - 0 === i; - } - }, - filter: { - PSEUDO: function (elem, match, i, array) { - var name = match[1], - filter = Expr.filters[name]; - - if (filter) { - return filter(elem, i, match, array); - - } else if (name === "contains") { - return (elem.textContent || elem.innerText || getText([elem]) || "").indexOf(match[3]) >= 0; - - } else if (name === "not") { - var not = match[3]; - - for (var j = 0, l = not.length; j < l; j++) { - if (not[j] === elem) { - return false; - } - } - - return true; - - } else { - Sizzle.error(name); - } - }, - - CHILD: function (elem, match) { - var first, last, - doneName, parent, cache, - count, diff, - type = match[1], - node = elem; - - switch (type) { - case "only": - case "first": - while ((node = node.previousSibling)) { - if (node.nodeType === 1) { - return false; - } - } - - if (type === "first") { - return true; - } - - node = elem; - - case "last": - while ((node = node.nextSibling)) { - if (node.nodeType === 1) { - return false; - } - } - - return true; - - case "nth": - first = match[2]; - last = match[3]; - - if (first === 1 && last === 0) { - return true; - } - - doneName = match[0]; - parent = elem.parentNode; - - if (parent && (parent[expando] !== doneName || !elem.nodeIndex)) { - count = 0; - - for (node = parent.firstChild; node; node = node.nextSibling) { - if (node.nodeType === 1) { - node.nodeIndex = ++count; - } - } - - parent[expando] = doneName; - } - - diff = elem.nodeIndex - last; - - if (first === 0) { - return diff === 0; - - } else { - return (diff % first === 0 && diff / first >= 0); - } - } - }, - - ID: function (elem, match) { - return elem.nodeType === 1 && elem.getAttribute("id") === match; - }, - - TAG: function (elem, match) { - return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match; - }, - - CLASS: function (elem, match) { - return (" " + (elem.className || elem.getAttribute("class")) + " ") - .indexOf(match) > -1; - }, - - ATTR: function (elem, match) { - var name = match[1], - result = Sizzle.attr ? - Sizzle.attr(elem, name) : - Expr.attrHandle[name] ? - Expr.attrHandle[name](elem) : - elem[name] != null ? - elem[name] : - elem.getAttribute(name), - value = result + "", - type = match[2], - check = match[4]; - - return result == null ? - type === "!=" : - !type && Sizzle.attr ? - result != null : - type === "=" ? - value === check : - type === "*=" ? - value.indexOf(check) >= 0 : - type === "~=" ? - (" " + value + " ").indexOf(check) >= 0 : - !check ? - value && result !== false : - type === "!=" ? - value !== check : - type === "^=" ? - value.indexOf(check) === 0 : - type === "$=" ? - value.substr(value.length - check.length) === check : - type === "|=" ? - value === check || value.substr(0, check.length + 1) === check + "-" : - false; - }, - - POS: function (elem, match, i, array) { - var name = match[2], - filter = Expr.setFilters[name]; - - if (filter) { - return filter(elem, i, match, array); - } - } - } - }; - - var origPOS = Expr.match.POS, - fescape = function (all, num) { - return "\\" + (num - 0 + 1); - }; - - for (var type in Expr.match) { - Expr.match[type] = new RegExp(Expr.match[type].source + (/(?![^\[]*\])(?![^\(]*\))/.source)); - Expr.leftMatch[type] = new RegExp(/(^(?:.|\r|\n)*?)/.source + Expr.match[type].source.replace(/\\(\d+)/g, fescape)); - } - - var makeArray = function (array, results) { - array = Array.prototype.slice.call(array, 0); - - if (results) { - results.push.apply(results, array); - return results; - } - - return array; - }; - - // Perform a simple check to determine if the browser is capable of - // converting a NodeList to an array using builtin methods. - // Also verifies that the returned array holds DOM nodes - // (which is not the case in the Blackberry browser) - try { - Array.prototype.slice.call(document.documentElement.childNodes, 0)[0].nodeType; - - // Provide a fallback method if it does not work - } catch (e) { - makeArray = function (array, results) { - var i = 0, - ret = results || []; - - if (toString.call(array) === "[object Array]") { - Array.prototype.push.apply(ret, array); - - } else { - if (typeof array.length === "number") { - for (var l = array.length; i < l; i++) { - ret.push(array[i]); - } - - } else { - for (; array[i]; i++) { - ret.push(array[i]); - } - } - } - - return ret; - }; - } - - var sortOrder, siblingCheck; - - if (document.documentElement.compareDocumentPosition) { - sortOrder = function (a, b) { - if (a === b) { - hasDuplicate = true; - return 0; - } - - if (!a.compareDocumentPosition || !b.compareDocumentPosition) { - return a.compareDocumentPosition ? -1 : 1; - } - - return a.compareDocumentPosition(b) & 4 ? -1 : 1; - }; - - } else { - sortOrder = function (a, b) { - // The nodes are identical, we can exit early - if (a === b) { - hasDuplicate = true; - return 0; - - // Fallback to using sourceIndex (in IE) if it's available on both nodes - } else if (a.sourceIndex && b.sourceIndex) { - return a.sourceIndex - b.sourceIndex; - } - - var al, bl, - ap = [], - bp = [], - aup = a.parentNode, - bup = b.parentNode, - cur = aup; - - // If the nodes are siblings (or identical) we can do a quick check - if (aup === bup) { - return siblingCheck(a, b); - - // If no parents were found then the nodes are disconnected - } else if (!aup) { - return -1; - - } else if (!bup) { - return 1; - } - - // Otherwise they're somewhere else in the tree so we need - // to build up a full list of the parentNodes for comparison - while (cur) { - ap.unshift(cur); - cur = cur.parentNode; - } - - cur = bup; - - while (cur) { - bp.unshift(cur); - cur = cur.parentNode; - } - - al = ap.length; - bl = bp.length; - - // Start walking down the tree looking for a discrepancy - for (var i = 0; i < al && i < bl; i++) { - if (ap[i] !== bp[i]) { - return siblingCheck(ap[i], bp[i]); - } - } - - // We ended someplace up the tree so do a sibling check - return i === al ? - siblingCheck(a, bp[i], -1) : - siblingCheck(ap[i], b, 1); - }; - - siblingCheck = function (a, b, ret) { - if (a === b) { - return ret; - } - - var cur = a.nextSibling; - - while (cur) { - if (cur === b) { - return -1; - } - - cur = cur.nextSibling; - } - - return 1; - }; - } - - // Check to see if the browser returns elements by name when - // querying by getElementById (and provide a workaround) - (function () { - // We're going to inject a fake input element with a specified name - var form = document.createElement("div"), - id = "script" + (new Date()).getTime(), - root = document.documentElement; - - form.innerHTML = ""; - - // Inject it into the root element, check its status, and remove it quickly - root.insertBefore(form, root.firstChild); - - // The workaround has to do additional checks after a getElementById - // Which slows things down for other browsers (hence the branching) - if (document.getElementById(id)) { - Expr.find.ID = function (match, context, isXML) { - if (typeof context.getElementById !== "undefined" && !isXML) { - var m = context.getElementById(match[1]); - - return m ? - m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? - [m] : - undefined : - []; - } - }; - - Expr.filter.ID = function (elem, match) { - var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); - - return elem.nodeType === 1 && node && node.nodeValue === match; - }; - } - - root.removeChild(form); - - // release memory in IE - root = form = null; - })(); - - (function () { - // Check to see if the browser returns only elements - // when doing getElementsByTagName("*") - - // Create a fake element - var div = document.createElement("div"); - div.appendChild(document.createComment("")); - - // Make sure no comments are found - if (div.getElementsByTagName("*").length > 0) { - Expr.find.TAG = function (match, context) { - var results = context.getElementsByTagName(match[1]); - - // Filter out possible comments - if (match[1] === "*") { - var tmp = []; - - for (var i = 0; results[i]; i++) { - if (results[i].nodeType === 1) { - tmp.push(results[i]); - } - } - - results = tmp; - } - - return results; - }; - } - - // Check to see if an attribute returns normalized href attributes - div.innerHTML = ""; - - if (div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && - div.firstChild.getAttribute("href") !== "#") { - - Expr.attrHandle.href = function (elem) { - return elem.getAttribute("href", 2); - }; - } - - // release memory in IE - div = null; - })(); - - if (document.querySelectorAll) { - (function () { - var oldSizzle = Sizzle, - div = document.createElement("div"), - id = "__sizzle__"; - - div.innerHTML = "

"; - - // Safari can't handle uppercase or unicode characters when - // in quirks mode. - if (div.querySelectorAll && div.querySelectorAll(".TEST").length === 0) { - return; - } - - Sizzle = function (query, context, extra, seed) { - context = context || document; - - // Only use querySelectorAll on non-XML documents - // (ID selectors don't work in non-HTML documents) - if (!seed && !Sizzle.isXML(context)) { - // See if we find a selector to speed up - var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(query); - - if (match && (context.nodeType === 1 || context.nodeType === 9)) { - // Speed-up: Sizzle("TAG") - if (match[1]) { - return makeArray(context.getElementsByTagName(query), extra); - - // Speed-up: Sizzle(".CLASS") - } else if (match[2] && Expr.find.CLASS && context.getElementsByClassName) { - return makeArray(context.getElementsByClassName(match[2]), extra); - } - } - - if (context.nodeType === 9) { - // Speed-up: Sizzle("body") - // The body element only exists once, optimize finding it - if (query === "body" && context.body) { - return makeArray([context.body], extra); - - // Speed-up: Sizzle("#ID") - } else if (match && match[3]) { - var elem = context.getElementById(match[3]); - - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if (elem && elem.parentNode) { - // Handle the case where IE and Opera return items - // by name instead of ID - if (elem.id === match[3]) { - return makeArray([elem], extra); - } - - } else { - return makeArray([], extra); - } - } - - try { - return makeArray(context.querySelectorAll(query), extra); - } catch (qsaError) { } - - // qSA works strangely on Element-rooted queries - // We can work around this by specifying an extra ID on the root - // and working up from there (Thanks to Andrew Dupont for the technique) - // IE 8 doesn't work on object elements - } else if (context.nodeType === 1 && context.nodeName.toLowerCase() !== "object") { - var oldContext = context, - old = context.getAttribute("id"), - nid = old || id, - hasParent = context.parentNode, - relativeHierarchySelector = /^\s*[+~]/.test(query); - - if (!old) { - context.setAttribute("id", nid); - } else { - nid = nid.replace(/'/g, "\\$&"); - } - if (relativeHierarchySelector && hasParent) { - context = context.parentNode; - } - - try { - if (!relativeHierarchySelector || hasParent) { - return makeArray(context.querySelectorAll("[id='" + nid + "'] " + query), extra); - } - - } catch (pseudoError) { - } finally { - if (!old) { - oldContext.removeAttribute("id"); - } - } - } - } - - return oldSizzle(query, context, extra, seed); - }; - - for (var prop in oldSizzle) { - Sizzle[prop] = oldSizzle[prop]; - } - - // release memory in IE - div = null; - })(); - } - - (function () { - var html = document.documentElement, - matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; - - if (matches) { - // Check to see if it's possible to do matchesSelector - // on a disconnected node (IE 9 fails this) - var disconnectedMatch = !matches.call(document.createElement("div"), "div"), - pseudoWorks = false; - - try { - // This should fail with an exception - // Gecko does not error, returns false instead - matches.call(document.documentElement, "[test!='']:sizzle"); - - } catch (pseudoError) { - pseudoWorks = true; - } - - Sizzle.matchesSelector = function (node, expr) { - // Make sure that attribute selectors are quoted - expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); - - if (!Sizzle.isXML(node)) { - try { - if (pseudoWorks || !Expr.match.PSEUDO.test(expr) && !/!=/.test(expr)) { - var ret = matches.call(node, expr); - - // IE 9's matchesSelector returns false on disconnected nodes - if (ret || !disconnectedMatch || - // As well, disconnected nodes are said to be in a document - // fragment in IE 9, so check for that - node.document && node.document.nodeType !== 11) { - return ret; - } - } - } catch (e) { } - } - - return Sizzle(expr, null, null, [node]).length > 0; - }; - } - })(); - - (function () { - var div = document.createElement("div"); - - div.innerHTML = "
"; - - // Opera can't find a second classname (in 9.6) - // Also, make sure that getElementsByClassName actually exists - if (!div.getElementsByClassName || div.getElementsByClassName("e").length === 0) { - return; - } - - // Safari caches class attributes, doesn't catch changes (in 3.2) - div.lastChild.className = "e"; - - if (div.getElementsByClassName("e").length === 1) { - return; - } - - Expr.order.splice(1, 0, "CLASS"); - Expr.find.CLASS = function (match, context, isXML) { - if (typeof context.getElementsByClassName !== "undefined" && !isXML) { - return context.getElementsByClassName(match[1]); - } - }; - - // release memory in IE - div = null; - })(); - - function dirNodeCheck(dir, cur, doneName, checkSet, nodeCheck, isXML) { - for (var i = 0, l = checkSet.length; i < l; i++) { - var elem = checkSet[i]; - - if (elem) { - var match = false; - - elem = elem[dir]; - - while (elem) { - if (elem[expando] === doneName) { - match = checkSet[elem.sizset]; - break; - } - - if (elem.nodeType === 1 && !isXML) { - elem[expando] = doneName; - elem.sizset = i; - } - - if (elem.nodeName.toLowerCase() === cur) { - match = elem; - break; - } - - elem = elem[dir]; - } - - checkSet[i] = match; - } - } - } - - function dirCheck(dir, cur, doneName, checkSet, nodeCheck, isXML) { - for (var i = 0, l = checkSet.length; i < l; i++) { - var elem = checkSet[i]; - - if (elem) { - var match = false; - - elem = elem[dir]; - - while (elem) { - if (elem[expando] === doneName) { - match = checkSet[elem.sizset]; - break; - } - - if (elem.nodeType === 1) { - if (!isXML) { - elem[expando] = doneName; - elem.sizset = i; - } - - if (typeof cur !== "string") { - if (elem === cur) { - match = true; - break; - } - - } else if (Sizzle.filter(cur, [elem]).length > 0) { - match = elem; - break; - } - } - - elem = elem[dir]; - } - - checkSet[i] = match; - } - } - } - - if (document.documentElement.contains) { - Sizzle.contains = function (a, b) { - return a !== b && (a.contains ? a.contains(b) : true); - }; - - } else if (document.documentElement.compareDocumentPosition) { - Sizzle.contains = function (a, b) { - return !!(a.compareDocumentPosition(b) & 16); - }; - - } else { - Sizzle.contains = function () { - return false; - }; - } - - Sizzle.isXML = function (elem) { - // documentElement is verified for cases where it doesn't yet exist - // (such as loading iframes in IE - #4833) - var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; - - return documentElement ? documentElement.nodeName !== "HTML" : false; - }; - - var posProcess = function (selector, context, seed) { - var match, - tmpSet = [], - later = "", - root = context.nodeType ? [context] : context; - - // Position selectors must be done after the filter - // And so must :not(positional) so we move all PSEUDOs to the end - while ((match = Expr.match.PSEUDO.exec(selector))) { - later += match[0]; - selector = selector.replace(Expr.match.PSEUDO, ""); - } - - selector = Expr.relative[selector] ? selector + "*" : selector; - - for (var i = 0, l = root.length; i < l; i++) { - Sizzle(selector, root[i], tmpSet, seed); - } - - return Sizzle.filter(later, tmpSet); - }; - - // EXPOSE - // Override sizzle attribute retrieval - Sizzle.attr = jQuery.attr; - Sizzle.selectors.attrMap = {}; - jQuery.find = Sizzle; - jQuery.expr = Sizzle.selectors; - jQuery.expr[":"] = jQuery.expr.filters; - jQuery.unique = Sizzle.uniqueSort; - jQuery.text = Sizzle.getText; - jQuery.isXMLDoc = Sizzle.isXML; - jQuery.contains = Sizzle.contains; - - - })(); - - - var runtil = /Until$/, - rparentsprev = /^(?:parents|prevUntil|prevAll)/, - // Note: This RegExp should be improved, or likely pulled from Sizzle - rmultiselector = /,/, - isSimple = /^.[^:#\[\.,]*$/, - slice = Array.prototype.slice, - POS = jQuery.expr.match.POS, - // methods guaranteed to produce a unique set when starting from a unique set - guaranteedUnique = { - children: true, - contents: true, - next: true, - prev: true - }; - - jQuery.fn.extend({ - find: function (selector) { - var self = this, - i, l; - - if (typeof selector !== "string") { - return jQuery(selector).filter(function () { - for (i = 0, l = self.length; i < l; i++) { - if (jQuery.contains(self[i], this)) { - return true; - } - } - }); - } - - var ret = this.pushStack("", "find", selector), - length, n, r; - - for (i = 0, l = this.length; i < l; i++) { - length = ret.length; - jQuery.find(selector, this[i], ret); - - if (i > 0) { - // Make sure that the results are unique - for (n = length; n < ret.length; n++) { - for (r = 0; r < length; r++) { - if (ret[r] === ret[n]) { - ret.splice(n--, 1); - break; - } - } - } - } - } - - return ret; - }, - - has: function (target) { - var targets = jQuery(target); - return this.filter(function () { - for (var i = 0, l = targets.length; i < l; i++) { - if (jQuery.contains(this, targets[i])) { - return true; - } - } - }); - }, - - not: function (selector) { - return this.pushStack(winnow(this, selector, false), "not", selector); - }, - - filter: function (selector) { - return this.pushStack(winnow(this, selector, true), "filter", selector); - }, - - is: function (selector) { - return !!selector && ( - typeof selector === "string" ? - // If this is a positional selector, check membership in the returned set - // so $("p:first").is("p:last") won't return true for a doc with two "p". - POS.test(selector) ? - jQuery(selector, this.context).index(this[0]) >= 0 : - jQuery.filter(selector, this).length > 0 : - this.filter(selector).length > 0); - }, - - closest: function (selectors, context) { - var ret = [], i, l, cur = this[0]; - - // Array (deprecated as of jQuery 1.7) - if (jQuery.isArray(selectors)) { - var level = 1; - - while (cur && cur.ownerDocument && cur !== context) { - for (i = 0; i < selectors.length; i++) { - - if (jQuery(cur).is(selectors[i])) { - ret.push({ selector: selectors[i], elem: cur, level: level }); - } - } - - cur = cur.parentNode; - level++; - } - - return ret; - } - - // String - var pos = POS.test(selectors) || typeof selectors !== "string" ? - jQuery(selectors, context || this.context) : - 0; - - for (i = 0, l = this.length; i < l; i++) { - cur = this[i]; - - while (cur) { - if (pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors)) { - ret.push(cur); - break; - - } else { - cur = cur.parentNode; - if (!cur || !cur.ownerDocument || cur === context || cur.nodeType === 11) { - break; - } - } - } - } - - ret = ret.length > 1 ? jQuery.unique(ret) : ret; - - return this.pushStack(ret, "closest", selectors); - }, - - // Determine the position of an element within - // the matched set of elements - index: function (elem) { - - // No argument, return index in parent - if (!elem) { - return (this[0] && this[0].parentNode) ? this.prevAll().length : -1; - } - - // index in selector - if (typeof elem === "string") { - return jQuery.inArray(this[0], jQuery(elem)); - } - - // Locate the position of the desired element - return jQuery.inArray( - // If it receives a jQuery object, the first element is used - elem.jquery ? elem[0] : elem, this); - }, - - add: function (selector, context) { - var set = typeof selector === "string" ? - jQuery(selector, context) : - jQuery.makeArray(selector && selector.nodeType ? [selector] : selector), - all = jQuery.merge(this.get(), set); - - return this.pushStack(isDisconnected(set[0]) || isDisconnected(all[0]) ? - all : - jQuery.unique(all)); - }, - - andSelf: function () { - return this.add(this.prevObject); - } - }); - - // A painfully simple check to see if an element is disconnected - // from a document (should be improved, where feasible). - function isDisconnected(node) { - return !node || !node.parentNode || node.parentNode.nodeType === 11; - } - - jQuery.each({ - parent: function (elem) { - var parent = elem.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; - }, - parents: function (elem) { - return jQuery.dir(elem, "parentNode"); - }, - parentsUntil: function (elem, i, until) { - return jQuery.dir(elem, "parentNode", until); - }, - next: function (elem) { - return jQuery.nth(elem, 2, "nextSibling"); - }, - prev: function (elem) { - return jQuery.nth(elem, 2, "previousSibling"); - }, - nextAll: function (elem) { - return jQuery.dir(elem, "nextSibling"); - }, - prevAll: function (elem) { - return jQuery.dir(elem, "previousSibling"); - }, - nextUntil: function (elem, i, until) { - return jQuery.dir(elem, "nextSibling", until); - }, - prevUntil: function (elem, i, until) { - return jQuery.dir(elem, "previousSibling", until); - }, - siblings: function (elem) { - return jQuery.sibling(elem.parentNode.firstChild, elem); - }, - children: function (elem) { - return jQuery.sibling(elem.firstChild); - }, - contents: function (elem) { - return jQuery.nodeName(elem, "iframe") ? - elem.contentDocument || elem.contentWindow.document : - jQuery.makeArray(elem.childNodes); - } - }, function (name, fn) { - jQuery.fn[name] = function (until, selector) { - var ret = jQuery.map(this, fn, until); - - if (!runtil.test(name)) { - selector = until; - } - - if (selector && typeof selector === "string") { - ret = jQuery.filter(selector, ret); - } - - ret = this.length > 1 && !guaranteedUnique[name] ? jQuery.unique(ret) : ret; - - if ((this.length > 1 || rmultiselector.test(selector)) && rparentsprev.test(name)) { - ret = ret.reverse(); - } - - return this.pushStack(ret, name, slice.call(arguments).join(",")); - }; - }); - - jQuery.extend({ - filter: function (expr, elems, not) { - if (not) { - expr = ":not(" + expr + ")"; - } - - return elems.length === 1 ? - jQuery.find.matchesSelector(elems[0], expr) ? [elems[0]] : [] : - jQuery.find.matches(expr, elems); - }, - - dir: function (elem, dir, until) { - var matched = [], - cur = elem[dir]; - - while (cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery(cur).is(until))) { - if (cur.nodeType === 1) { - matched.push(cur); - } - cur = cur[dir]; - } - return matched; - }, - - nth: function (cur, result, dir, elem) { - result = result || 1; - var num = 0; - - for (; cur; cur = cur[dir]) { - if (cur.nodeType === 1 && ++num === result) { - break; - } - } - - return cur; - }, - - sibling: function (n, elem) { - var r = []; - - for (; n; n = n.nextSibling) { - if (n.nodeType === 1 && n !== elem) { - r.push(n); - } - } - - return r; - } - }); - - // Implement the identical functionality for filter and not - function winnow(elements, qualifier, keep) { - - // Can't pass null or undefined to indexOf in Firefox 4 - // Set to 0 to skip string check - qualifier = qualifier || 0; - - if (jQuery.isFunction(qualifier)) { - return jQuery.grep(elements, function (elem, i) { - var retVal = !!qualifier.call(elem, i, elem); - return retVal === keep; - }); - - } else if (qualifier.nodeType) { - return jQuery.grep(elements, function (elem, i) { - return (elem === qualifier) === keep; - }); - - } else if (typeof qualifier === "string") { - var filtered = jQuery.grep(elements, function (elem) { - return elem.nodeType === 1; - }); - - if (isSimple.test(qualifier)) { - return jQuery.filter(qualifier, filtered, !keep); - } else { - qualifier = jQuery.filter(qualifier, filtered); - } - } - - return jQuery.grep(elements, function (elem, i) { - return (jQuery.inArray(elem, qualifier) >= 0) === keep; - }); - } - - - - - function createSafeFragment(document) { - var list = nodeNames.split("|"), - safeFrag = document.createDocumentFragment(); - - if (safeFrag.createElement) { - while (list.length) { - safeFrag.createElement( - list.pop() - ); - } - } - return safeFrag; - } - - var nodeNames = "abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|" + - "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", - rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, - rleadingWhitespace = /^\s+/, - rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, - rtagName = /<([\w:]+)/, - rtbody = /", ""], - legend: [1, "
", "
"], - thead: [1, "", "
"], - tr: [2, "", "
"], - td: [3, "", "
"], - col: [2, "", "
"], - area: [1, "", ""], - _default: [0, "", ""] - }, - safeFragment = createSafeFragment(document); - - wrapMap.optgroup = wrapMap.option; - wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; - wrapMap.th = wrapMap.td; - - // IE can't serialize and + + - + diff --git a/Tests/validation-tests.js b/Tests/validation-tests.js index df6524f5..c234200c 100644 --- a/Tests/validation-tests.js +++ b/Tests/validation-tests.js @@ -7,7 +7,8 @@ ok:false, asyncTest:false, start: false, - stop: false + stop: false, + expect: false */ //#region Required Validation @@ -319,6 +320,8 @@ test('Pattern validation doesn\'t break with non-string values', function () { testObj({}); testObj.isValid(); + + expect(0); }); //#endregion @@ -1345,5 +1348,4 @@ asyncTest('Async Rule Is NOT Valid Test', function () { testObj.extend({ mustEqualAsync: 5 }); }); - //#endregion diff --git a/Tests/validation-ui-tests.js b/Tests/validation-ui-tests.js index 75db9126..0ecac833 100644 --- a/Tests/validation-ui-tests.js +++ b/Tests/validation-ui-tests.js @@ -8,7 +8,8 @@ asyncTest:false, start: false, stop: false, - $: false + $: false, + expect: false */ module('UI Tests', { diff --git a/gruntfile.js b/gruntfile.js index f32a7b4b..bd180283 100644 --- a/gruntfile.js +++ b/gruntfile.js @@ -5,14 +5,12 @@ module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON("package.json"), meta: { - banner: "/*\n" + - "===============================================================================\n" + + banner: "/*=============================================================================\n" + " Author: Eric M. Barnard - @ericmbarnard \n" + " License: MIT (http://opensource.org/licenses/mit-license.php) \n" + " \n" + " Description: Validation Library for KnockoutJS \n" + - "===============================================================================\n" + - "*/" + "===============================================================================\n*/\n" }, concat: { options: { diff --git a/package.json b/package.json index 79452ac7..70a0c43f 100644 --- a/package.json +++ b/package.json @@ -18,7 +18,7 @@ "grunt-clear": "~0.2.1" }, "scripts": { - "test": "grunt test --verbose" + "test": "grunt test" }, "repository": { "type": "git", From 48e486b099dffe113210b032a311659cfda8149f Mon Sep 17 00:00:00 2001 From: Steve Greatrex Date: Sat, 5 Oct 2013 14:24:04 +0100 Subject: [PATCH 033/165] Added travis CI config --- .travis.yml | 3 +++ Src/knockout.validation.js | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) create mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..87f8cd91 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - "0.10" \ No newline at end of file diff --git a/Src/knockout.validation.js b/Src/knockout.validation.js index 8017858b..cd834d32 100644 --- a/Src/knockout.validation.js +++ b/Src/knockout.validation.js @@ -587,7 +587,7 @@ // 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 (utils.isEmptyVal(val) || step == 'any') return true; + if (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; }, From dc30fbba158a3116ecee07ec91fb267ac5e8f79d Mon Sep 17 00:00:00 2001 From: Steve Greatrex Date: Sat, 5 Oct 2013 15:46:30 +0100 Subject: [PATCH 034/165] Split source into multiple files for better maintenance --- Dist/knockout.validation.js | 2175 +++++++++++++-------------- Dist/knockout.validation.min.js | 10 +- Dist/knockout.validation.min.js.map | 8 + Src/api.js | 337 +++++ Src/bindingHandlers.js | 157 ++ Src/configuration.js | 33 + Src/extenders.js | 193 +++ Src/knockout.validation.js | 1128 -------------- Src/ko.extensions.js | 44 + Src/ko.validation.end.frag | 1 + Src/ko.validation.start.frag | 21 + Src/localization.js | 13 + Src/rules.js | 194 +++ Src/utils.js | 102 ++ Tests/test-runner.htm | 2 +- gruntfile.js | 15 +- 16 files changed, 2187 insertions(+), 2246 deletions(-) create mode 100644 Dist/knockout.validation.min.js.map create mode 100644 Src/api.js create mode 100644 Src/bindingHandlers.js create mode 100644 Src/configuration.js create mode 100644 Src/extenders.js delete mode 100644 Src/knockout.validation.js create mode 100644 Src/ko.extensions.js create mode 100644 Src/ko.validation.end.frag create mode 100644 Src/ko.validation.start.frag create mode 100644 Src/localization.js create mode 100644 Src/rules.js create mode 100644 Src/utils.js diff --git a/Dist/knockout.validation.js b/Dist/knockout.validation.js index f859b319..cd20bb9e 100644 --- a/Dist/knockout.validation.js +++ b/Dist/knockout.validation.js @@ -5,12 +5,7 @@ Description: Validation Library for KnockoutJS =============================================================================== */ -/*globals - require: false, - exports: false, - define: false, - ko: false -*/ +/*globals require: false, exports: false, define: false, ko: false */ (function (factory) { // Module systems magic dance. @@ -30,1103 +25,1071 @@ if (typeof (ko) === undefined) { throw 'Knockout is required, please ensure it is loaded before loading this validation plug-in'; } // create our namespace object - var validation = exports; - ko.validation = validation; - - var defaults = { - registerExtenders: true, - messagesOnModified: true, - errorsAsTitle: true, // enables/disables showing of errors as title attribute of the target element. - errorsAsTitleOnModified: false, // shows the error when hovering the input field (decorateElement must be true) - messageTemplate: null, - insertMessages: true, // automatically inserts validation messages as - parseInputAttributes: false, // parses the HTML5 validation attribute from a form element and adds that to the object - writeInputAttributes: false, // adds HTML5 input validation attributes to form elements that ko observable's are bound to - decorateElement: false, // false to keep backward compatibility - errorClass: null, // single class for error message and element - errorElementClass: 'validationElement', // class to decorate error element - errorMessageClass: 'validationMessage', // class to decorate error message - grouping: { - deep: false, //by default grouping is shallow - observable: true //and using observables - } - }; - - // make a copy so we can use 'reset' later - var configuration = ko.utils.extend({}, defaults); - - var html5Attributes = ['required', 'pattern', 'min', 'max', 'step']; - var html5InputTypes = ['email', 'number', 'date']; - - var async = function (expr) { - if (window.setImmediate) { window.setImmediate(expr); } - else { window.setTimeout(expr, 0); } - }; - - //#region Utilities - - var utils = (function () { - var seedId = new Date().getTime(); - - var domData = {}; //hash of data objects that we reference from dom elements - var domDataKey = '__ko_validation__'; - - return { - isArray: function (o) { - return o.isArray || Object.prototype.toString.call(o) === '[object Array]'; - }, - isObject: function (o) { - return o !== null && typeof o === 'object'; - }, - values: function (o) { - var r = []; - for (var i in o) { - if (o.hasOwnProperty(i)) { - r.push(o[i]); - } - } - return r; - }, - getValue: function (o) { - return (typeof o === 'function' ? o() : o); - }, - hasAttribute: function (node, attr) { - return node.getAttribute(attr) !== null; - }, - getAttribute: function(element, attr){ - return element.getAttribute(attr); - }, - setAttribute: function(element, attr, value){ - return element.setAttribute(attr, value); - }, - isValidatable: function (o) { - return o && o.rules && o.isValid && o.isModified; - }, - insertAfter: function (node, newNode) { - node.parentNode.insertBefore(newNode, node.nextSibling); - }, - newId: function () { - return seedId += 1; - }, - getConfigOptions: function (element) { - var options = utils.contextFor(element); - - return options || configuration; - }, - setDomData: function (node, data) { - var key = node[domDataKey]; - - if (!key) { - node[domDataKey] = key = utils.newId(); - } - - domData[key] = data; - }, - getDomData: function (node) { - var key = node[domDataKey]; - - if (!key) { - return undefined; - } - - return domData[key]; - }, - contextFor: function (node) { - switch (node.nodeType) { - case 1: - case 8: - var context = utils.getDomData(node); - if (context) { return context; } - if (node.parentNode) { return utils.contextFor(node.parentNode); } - break; - } - return undefined; - }, - isEmptyVal: function (val) { - if (val === undefined) { - return true; - } - if (val === null) { - return true; - } - if (val === "") { - return true; - } - }, - getOriginalElementTitle: function (element) { - var savedOriginalTitle = utils.getAttribute(element, 'data-orig-title'), - currentTitle = element.title, - hasSavedOriginalTitle = utils.hasAttribute(element, 'data-orig-title'); - - return hasSavedOriginalTitle ? - savedOriginalTitle : currentTitle; - } - }; - } ()); - - //#endregion - - //#region Public API - var api = (function () { - - var isInitialized = 0; - - return { - utils: utils, - - //Call this on startup - //any config can be overridden with the passed in options - init: function (options, force) { - //done run this multiple times if we don't really want to - if (isInitialized > 0 && !force) { - return; - } - - //becuase we will be accessing options properties it has to be an object at least - options = options || {}; - //if specific error classes are not provided then apply generic errorClass - //it has to be done on option so that options.errorClass can override default - //errorElementClass and errorMessage class but not those provided in options - options.errorElementClass = options.errorElementClass || options.errorClass || configuration.errorElementClass; - options.errorMessageClass = options.errorMessageClass || options.errorClass || configuration.errorMessageClass; - - ko.utils.extend(configuration, options); - - if (configuration.registerExtenders) { - exports.registerExtenders(); - } - - isInitialized = 1; - }, - // backwards compatability - configure: function (options) { exports.init(options); }, - - // resets the config back to its original state - reset: function () { configuration = jQuery.extend(configuration, defaults); }, - - // recursivly walks a viewModel and creates an object that - // provides validation information for the entire viewModel - // obj -> the viewModel to walk - // options -> { - // deep: false, // if true, will walk past the first level of viewModel properties - // observable: false // if true, returns a computed observable indicating if the viewModel is valid - // } - group: function group(obj, options) { // array of observables or viewModel - options = ko.utils.extend(ko.utils.extend({}, configuration.grouping), options); - - var validatables = ko.observableArray([]), - result = null, - - //anonymous, immediate function to traverse objects hierarchically - //if !options.deep then it will stop on top level - traverse = function traverse(obj, level) { - var objValues = [], - val = ko.utils.unwrapObservable(obj); - - //default level value depends on deep option. - level = (level !== undefined ? level : options.deep ? 1 : -1); - - // if object is observable then add it to the list - if (ko.isObservable(obj)) { - - //make sure it is validatable object - if (!obj.isValid) { obj.extend({ validatable: true }); } - validatables.push(obj); - } - - //get list of values either from array or object but ignore non-objects - if (val) { - if (utils.isArray(val)) { - objValues = val; - } else if (utils.isObject(val)) { - objValues = utils.values(val); - } - } - - //process recurisvely if it is deep grouping - if (level !== 0) { - ko.utils.arrayForEach(objValues, function (observable) { - - //but not falsy things and not HTML Elements - if (observable && !observable.nodeType) { traverse(observable, level + 1); } - }); - } - }; - - //if using observables then traverse structure once and add observables - if (options.observable) { - - traverse(obj); - - result = ko.computed(function () { - var errors = []; - ko.utils.arrayForEach(validatables(), function (observable) { - if (!observable.isValid()) { - errors.push(observable.error); - } - }); - return errors; - }); - - } else { //if not using observables then every call to error() should traverse the structure - result = function () { - var errors = []; - validatables([]); //clear validatables - traverse(obj); // and traverse tree again - ko.utils.arrayForEach(validatables(), function (observable) { - if (!observable.isValid()) { - errors.push(observable.error); - } - }); - return errors; - }; - - - } - - result.showAllMessages = function (show) { // thanks @heliosPortal - if (show === undefined) {//default to true - show = true; - } - - // ensure we have latest changes - result(); - - ko.utils.arrayForEach(validatables(), function (observable) { - observable.isModified(show); - }); - }; - - obj.errors = result; - obj.isValid = function () { - return obj.errors().length === 0; - }; - obj.isAnyMessageShown = function() { - var invalidAndModifiedPresent = false; - - // ensure we have latest changes - result(); - - ko.utils.arrayForEach(validatables(), function (observable) { - if (!observable.isValid() && observable.isModified()) { - invalidAndModifiedPresent = true; - } - }); - return invalidAndModifiedPresent; - }; - - return result; - }, - - formatMessage: function (message, params) { - if (typeof (message) === 'function') { - return message(params); - } - return message.replace(/\{0\}/gi, ko.utils.unwrapObservable(params)); - }, - - // addRule: - // This takes in a ko.observable and a Rule Context - which is just a rule name and params to supply to the validator - // ie: ko.validation.addRule(myObservable, { - // rule: 'required', - // params: true - // }); - // - addRule: function (observable, rule) { - observable.extend({ validatable: true }); - - //push a Rule Context to the observables local array of Rule Contexts - observable.rules.push(rule); - return observable; - }, - - // addAnonymousRule: - // Anonymous Rules essentially have all the properties of a Rule, but are only specific for a certain property - // and developers typically are wanting to add them on the fly or not register a rule with the 'ko.validation.rules' object - // - // Example: - // var test = ko.observable('something').extend{( - // validation: { - // validator: function(val, someOtherVal){ - // return true; - // }, - // message: "Something must be really wrong!', - // params: true - // } - // )}; - addAnonymousRule: function (observable, ruleObj) { - var ruleName = utils.newId(); - - if ( ruleObj['message'] === undefined ) { - ruleObj['message'] = 'Error'; - } - - //Create an anonymous rule to reference - exports.rules[ruleName] = ruleObj; - - //add the anonymous rule to the observable - exports.addRule(observable, { - rule: ruleName, - params: ruleObj.params - }); - }, - - addExtender: function (ruleName) { - ko.extenders[ruleName] = function (observable, params) { - //params can come in a few flavors - // 1. Just the params to be passed to the validator - // 2. An object containing the Message to be used and the Params to pass to the validator - // 3. A condition when the validation rule to be applied - // - // Example: - // var test = ko.observable(3).extend({ - // max: { - // message: 'This special field has a Max of {0}', - // params: 2, - // onlyIf: function() { - // return specialField.IsVisible(); - // } - // } - // )}; - // - if (params.message || params.onlyIf) { //if it has a message or condition object, then its an object literal to use - return exports.addRule(observable, { - rule: ruleName, - message: params.message, - params: utils.isEmptyVal(params.params) ? true : params.params, - condition: params.onlyIf - }); - } else { - return exports.addRule(observable, { - rule: ruleName, - params: params - }); - } - }; - }, - - // loops through all ko.validation.rules and adds them as extenders to - // ko.extenders - registerExtenders: function () { // root extenders optional, use 'validation' extender if would cause conflicts - if (configuration.registerExtenders) { - for (var ruleName in exports.rules) { - if (exports.rules.hasOwnProperty(ruleName)) { - if (!ko.extenders[ruleName]) { - exports.addExtender(ruleName); - } - } - } - } - }, - - //creates a span next to the @element with the specified error class - insertValidationMessage: function (element) { - var span = document.createElement('SPAN'); - span.className = utils.getConfigOptions(element).errorMessageClass; - utils.insertAfter(element, span); - return span; - }, - - // if html-5 validation attributes have been specified, this parses - // the attributes on @element - parseInputValidationAttributes: function (element, valueAccessor) { - ko.utils.arrayForEach(html5Attributes, function (attr) { - if (utils.hasAttribute(element, attr)) { - exports.addRule(valueAccessor(), { - rule: attr, - params: element.getAttribute(attr) || true - }); - } - }); - - var currentType = element.getAttribute('type'); - ko.utils.arrayForEach(html5InputTypes, function (type) { - if (type === currentType){ - exports.addRule(valueAccessor(), { - rule: (type === 'date')?'dateISO':type, - params: true - }); - } - }); - }, - - // writes html5 validation attributes on the element passed in - writeInputValidationAttributes: function (element, valueAccessor) { - var observable = valueAccessor(); - - if (!observable || !observable.rules) { - return; - } - - var contexts = observable.rules(); // observable array - - // loop through the attributes and add the information needed - ko.utils.arrayForEach(html5Attributes, function (attr) { - var params; - var ctx = ko.utils.arrayFirst(contexts, function (ctx) { - return ctx.rule.toLowerCase() === attr.toLowerCase(); - }); - - if (!ctx) { - return; - } - - params = ctx.params; - - // we have to do some special things for the pattern validation - if (ctx.rule === "pattern") { - if (ctx.params instanceof RegExp) { - params = ctx.params.source; // we need the pure string representation of the RegExpr without the //gi stuff - } - } - - // we have a rule matching a validation attribute at this point - // so lets add it to the element along with the params - element.setAttribute(attr, params); - }); - - contexts = null; - }, - - //take an existing binding handler and make it cause automatic validations - makeBindingHandlerValidatable: function (handlerName) { - var init = ko.bindingHandlers[handlerName].init; - - ko.bindingHandlers[handlerName].init = function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { - - init(element, valueAccessor, allBindingsAccessor); - - return ko.bindingHandlers['validationCore'].init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext); - }; - } - }; - }()); - - // expose api publicly - ko.utils.extend(validation, api); - //#endregion - - //#region Core Validation Rules - - //Validation Rules: - // You can view and override messages or rules via: - // ko.validation.rules[ruleName] - // - // To implement a custom Rule, simply use this template: - // ko.validation.rules[''] = { - // validator: function (val, param) { - // - // return ; - // }, - // message: '' //optionally you can also use a '{0}' to denote a placeholder that will be replaced with your 'param' - // }; - // - // Example: - // ko.validation.rules['mustEqual'] = { - // validator: function( val, mustEqualVal ){ - // return val === mustEqualVal; - // }, - // message: 'This field must equal {0}' - // }; - // - validation.rules = {}; - validation.rules['required'] = { - validator: function (val, required) { - var stringTrimRegEx = /^\s+|\s+$/g, - testVal; - - if (val === undefined || val === null) { - return !required; - } - - testVal = val; - if (typeof (val) === "string") { - testVal = val.replace(stringTrimRegEx, ''); - } - - if (!required) {// if they passed: { required: false }, then don't require this - return true; - } - - return ((testVal + '').length > 0); - }, - message: 'This field is required.' - }; - - validation.rules['min'] = { - validator: function (val, min) { - return utils.isEmptyVal(val) || val >= min; - }, - message: 'Please enter a value greater than or equal to {0}.' - }; - - validation.rules['max'] = { - validator: function (val, max) { - return utils.isEmptyVal(val) || val <= max; - }, - message: 'Please enter a value less than or equal to {0}.' - }; - - validation.rules['minLength'] = { - validator: function (val, minLength) { - return utils.isEmptyVal(val) || val.length >= minLength; - }, - message: 'Please enter at least {0} characters.' - }; - - validation.rules['maxLength'] = { - validator: function (val, maxLength) { - return utils.isEmptyVal(val) || val.length <= maxLength; - }, - message: 'Please enter no more than {0} characters.' - }; - - validation.rules['pattern'] = { - validator: function (val, regex) { - return utils.isEmptyVal(val) || val.toString().match(regex) !== null; - }, - message: 'Please check this value.' - }; - - validation.rules['step'] = { - validator: function (val, step) { - - // 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 - return utils.isEmptyVal(val) || (val * 100) % (step * 100) === 0; - }, - message: 'The value must increment by {0}' - }; - - validation.rules['email'] = { - validator: function (val, validate) { - if (!validate) { return true; } - - //I think an empty email address is also a valid entry - //if one want's to enforce entry it should be done with 'required: true' - return utils.isEmptyVal(val) || ( - // jquery validate regex - thanks Scott Gonzalez - validate && /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(val) - ); - }, - message: 'Please enter a proper email address' - }; - - validation.rules['date'] = { - validator: function (value, validate) { - if (!validate) { return true; } - return utils.isEmptyVal(value) || (validate && !/Invalid|NaN/.test(new Date(value))); - }, - message: 'Please enter a proper date' - }; - - validation.rules['dateISO'] = { - validator: function (value, validate) { - if (!validate) { return true; } - return utils.isEmptyVal(value) || (validate && /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(value)); - }, - message: 'Please enter a proper date' - }; - - validation.rules['number'] = { - validator: function (value, validate) { - if (!validate) { return true; } - return utils.isEmptyVal(value) || (validate && /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value)); - }, - message: 'Please enter a number' - }; - - validation.rules['digit'] = { - validator: function (value, validate) { - if (!validate) { return true; } - return utils.isEmptyVal(value) || (validate && /^\d+$/.test(value)); - }, - message: 'Please enter a digit' - }; - - validation.rules['phoneUS'] = { - validator: function (phoneNumber, validate) { - if (!validate) { return true; } - if (typeof (phoneNumber) !== 'string') { return false; } - if (utils.isEmptyVal(phoneNumber)) { return true; } // makes it optional, use 'required' rule if it should be required - phoneNumber = phoneNumber.replace(/\s+/g, ""); - return validate && phoneNumber.length > 9 && phoneNumber.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/); - }, - message: 'Please specify a valid phone number' - }; - - validation.rules['equal'] = { - validator: function (val, params) { - var otherValue = params; - return val === utils.getValue(otherValue); - }, - message: 'Values must equal' - }; - - validation.rules['notEqual'] = { - validator: function (val, params) { - var otherValue = params; - return val !== utils.getValue(otherValue); - }, - message: 'Please choose another value.' - }; - - //unique in collection - // options are: - // collection: array or function returning (observable) array - // in which the value has to be unique - // valueAccessor: function that returns value from an object stored in collection - // if it is null the value is compared directly - // external: set to true when object you are validating is automatically updating collection - validation.rules['unique'] = { - validator: function (val, options) { - var c = utils.getValue(options.collection), - external = utils.getValue(options.externalValue), - counter = 0; - - if (!val || !c) { return true; } - - ko.utils.arrayFilter(ko.utils.unwrapObservable(c), function (item) { - if (val === (options.valueAccessor ? options.valueAccessor(item) : item)) { counter++; } - }); - // if value is external even 1 same value in collection means the value is not unique - return counter < (external !== undefined && val !== external ? 1 : 2); - }, - message: 'Please make sure the value is unique.' - }; - - - //now register all of these! - (function () { - validation.registerExtenders(); - } ()); - - //#endregion - - //#region Knockout Binding Handlers - - // The core binding handler - // this allows us to setup any value binding that internally always - // performs the same functionality - ko.bindingHandlers['validationCore'] = (function () { - - return { - init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { - var config = utils.getConfigOptions(element); - - // parse html5 input validation attributes, optional feature - if (config.parseInputAttributes) { - async(function () { exports.parseInputValidationAttributes(element, valueAccessor); }); - } - - // if requested insert message element and apply bindings - if (config.insertMessages && utils.isValidatable(valueAccessor())) { - - // insert the - var validationMessageElement = exports.insertValidationMessage(element); - - // if we're told to use a template, make sure that gets rendered - if (config.messageTemplate) { - ko.renderTemplate(config.messageTemplate, { field: valueAccessor() }, null, validationMessageElement, 'replaceNode'); - } else { - ko.applyBindingsToNode(validationMessageElement, { validationMessage: valueAccessor() }); - } - } - - // write the html5 attributes if indicated by the config - if (config.writeInputAttributes && utils.isValidatable(valueAccessor())) { - - exports.writeInputValidationAttributes(element, valueAccessor); - } - - // if requested, add binding to decorate element - if (config.decorateElement && utils.isValidatable(valueAccessor())) { - ko.applyBindingsToNode(element, { validationElement: valueAccessor() }); - } - }, - - update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { - // hook for future extensibility - } - }; - - }()); - - // override for KO's default 'value' and 'checked' bindings - api.makeBindingHandlerValidatable("value"); - api.makeBindingHandlerValidatable("checked"); - - - ko.bindingHandlers['validationMessage'] = { // individual error message, if modified or post binding - update: function (element, valueAccessor) { - var obsv = valueAccessor(), - config = utils.getConfigOptions(element), - val = ko.utils.unwrapObservable(obsv), - msg = null, - isModified = false, - isValid = false; - - obsv.extend({ validatable: true }); - - isModified = obsv.isModified(); - isValid = obsv.isValid(); - - // create a handler to correctly return an error message - var errorMsgAccessor = function () { - if (!config.messagesOnModified || isModified) { - return isValid ? null : obsv.error; - } else { - return null; - } - }; - - //toggle visibility on validation messages when validation hasn't been evaluated, or when the object isValid - var visiblityAccessor = function () { - return (!config.messagesOnModified || isModified) ? !isValid : false; - }; - - ko.bindingHandlers.text.update(element, errorMsgAccessor); - ko.bindingHandlers.visible.update(element, visiblityAccessor); - } - }; - - ko.bindingHandlers['validationElement'] = { - update: function (element, valueAccessor) { - var obsv = valueAccessor(), - config = utils.getConfigOptions(element), - val = ko.utils.unwrapObservable(obsv), - msg = null, - isModified = false, - isValid = false; - - obsv.extend({ validatable: true }); - - isModified = obsv.isModified(); - isValid = obsv.isValid(); - - // create an evaluator function that will return something like: - // css: { validationElement: true } - var cssSettingsAccessor = function () { - var css = {}; - - var shouldShow = (isModified ? !isValid : false); - - if (!config.decorateElement) { shouldShow = false; } - - // css: { validationElement: false } - css[config.errorElementClass] = shouldShow; - - return css; - }; - - //add or remove class on the element; - ko.bindingHandlers.css.update(element, cssSettingsAccessor); - if (!config.errorsAsTitle) { return; } - - var origTitle = utils.getAttribute(element, 'data-orig-title'), - elementTitle = element.title, - titleIsErrorMsg = utils.getAttribute(element, 'data-orig-title') === "true"; - - var errorMsgTitleAccessor = function () { - if (!config.errorsAsTitleOnModified || isModified) { - if (!isValid) { - return { title: obsv.error, 'data-orig-title': utils.getOriginalElementTitle(element) }; - } else { - return { title: utils.getOriginalElementTitle(element), 'data-orig-title': null }; - } - } - }; - ko.bindingHandlers.attr.update(element, errorMsgTitleAccessor); - } - }; - - // ValidationOptions: - // This binding handler allows you to override the initial config by setting any of the options for a specific element or context of elements - // - // Example: - //
- // - // - //
- ko.bindingHandlers['validationOptions'] = (function () { - return { - init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { - var options = ko.utils.unwrapObservable(valueAccessor()); - if (options) { - var newConfig = ko.utils.extend({}, configuration); - ko.utils.extend(newConfig, options); - - //store the validation options on the node so we can retrieve it later - utils.setDomData(element, newConfig); - } - } - }; - } ()); - //#endregion - - //#region Knockout Extenders - - // Validation Extender: - // This is for creating custom validation logic on the fly - // Example: - // var test = ko.observable('something').extend{( - // validation: { - // validator: function(val, someOtherVal){ - // return true; - // }, - // message: "Something must be really wrong!', - // params: true - // } - // )}; - ko.extenders['validation'] = function (observable, rules) { // allow single rule or array - ko.utils.arrayForEach(utils.isArray(rules) ? rules : [rules], function (rule) { - // the 'rule' being passed in here has no name to identify a core Rule, - // so we add it as an anonymous rule - // If the developer is wanting to use a core Rule, but use a different message see the 'addExtender' logic for examples - exports.addAnonymousRule(observable, rule); - }); - return observable; - }; - - //This is the extender that makes a Knockout Observable also 'Validatable' - //examples include: - // 1. var test = ko.observable('something').extend({validatable: true}); - // this will ensure that the Observable object is setup properly to respond to rules - // - // 2. test.extend({validatable: false}); - // this will remove the validation properties from the Observable object should you need to do that. - ko.extenders['validatable'] = function (observable, enable) { - if (enable && !utils.isValidatable(observable)) { - - observable.error = ko.observable(null); // holds the error message, we only need one since we stop processing validators when one is invalid - - // observable.rules: - // ObservableArray of Rule Contexts, where a Rule Context is simply the name of a rule and the params to supply to it - // - // Rule Context = { rule: '', params: '', message: '' } - observable.rules = ko.observableArray(); //holds the rule Contexts to use as part of validation - - //in case async validation is occuring - observable.isValidating = ko.observable(false); - - //the true holder of whether the observable is valid or not - observable.__valid__ = ko.observable(true); - - observable.isModified = ko.observable(false); - - // we use a computed here to ensure that anytime a dependency changes, the - // validation logic evaluates - var h_obsValidationTrigger = ko.computed(function () { - var obs = observable(), - ruleContexts = observable.rules(); - - exports.validateObservable(observable); - - return true; - }); - - // a semi-protected observable - observable.isValid = ko.computed(function () { - return observable.__valid__(); - }); - - //manually set error state - observable.setError = function (error) { - observable.error(error); - observable.__valid__(false); - }; - - //manually clear error state - observable.clearError = function () { - observable.error(null); - observable.__valid__(true); - }; - - //subscribe to changes in the observable - var h_change = observable.subscribe(function () { - observable.isModified(true); - }); - - observable._disposeValidation = function () { - //first dispose of the subscriptions - observable.isValid.dispose(); - observable.rules.removeAll(); - observable.isModified._subscriptions['change'] = []; - observable.isValidating._subscriptions['change'] = []; - observable.__valid__._subscriptions['change'] = []; - h_change.dispose(); - h_obsValidationTrigger.dispose(); - - delete observable['rules']; - delete observable['error']; - delete observable['isValid']; - delete observable['isValidating']; - delete observable['__valid__']; - delete observable['isModified']; - }; - } else if (enable === false && utils.isValidatable(observable)) { - - if (observable._disposeValidation) { - observable._disposeValidation(); - } - } - return observable; - }; - - function validateSync(observable, rule, ctx) { - //Execute the validator and see if its valid - if (!rule.validator(observable(), ctx.params === undefined ? true : ctx.params)) { // default param is true, eg. required = true - - //not valid, so format the error message and stick it in the 'error' variable - observable.error(exports.formatMessage(ctx.message || rule.message, ctx.params)); - observable.__valid__(false); - return false; - } else { - return true; - } - } - - function validateAsync(observable, rule, ctx) { - observable.isValidating(true); - - var callBack = function (valObj) { - var isValid = false, - msg = ''; - - if (!observable.__valid__()) { - - // since we're returning early, make sure we turn this off - observable.isValidating(false); - - return; //if its already NOT valid, don't add to that - } - - //we were handed back a complex object - if (valObj['message']) { - isValid = valObj.isValid; - msg = valObj.message; - } else { - isValid = valObj; - } - - if (!isValid) { - //not valid, so format the error message and stick it in the 'error' variable - observable.error(exports.formatMessage(msg || ctx.message || rule.message, ctx.params)); - observable.__valid__(isValid); - } - - // tell it that we're done - observable.isValidating(false); - }; - - //fire the validator and hand it the callback - rule.validator(observable(), ctx.params || true, callBack); - } - - validation.validateObservable = function (observable) { - var i = 0, - rule, // the rule validator to execute - ctx, // the current Rule Context for the loop - ruleContexts = observable.rules(), //cache for iterator - len = ruleContexts.length; //cache for iterator - - for (; i < len; i++) { - - //get the Rule Context info to give to the core Rule - ctx = ruleContexts[i]; - - // checks an 'onlyIf' condition - if (ctx.condition && !ctx.condition()) { - continue; - } - - //get the core Rule to use for validation - rule = exports.rules[ctx.rule]; - - if (rule['async'] || ctx['async']) { - //run async validation - validateAsync(observable, rule, ctx); - - } else { - //run normal sync validation - if (!validateSync(observable, rule, ctx)) { - return false; //break out of the loop - } - } - } - //finally if we got this far, make the observable valid again! - observable.error(null); - observable.__valid__(true); - return true; - }; - - //#endregion - - //#region Validated Observable - - ko.validatedObservable = function (initialValue) { - if (!exports.utils.isObject(initialValue)) { return ko.observable(initialValue).extend({ validatable: true }); } - - var obsv = ko.observable(initialValue); - obsv.errors = exports.group(initialValue); - obsv.isValid = ko.computed(function () { - return obsv.errors().length === 0; - }); - - return obsv; - }; - - //#endregion - - //#region Localization - - //quick function to override rule messages - validation.localize = function (msgTranslations) { - - var msg, rule; - - //loop the properties in the object and assign the msg to the rule - for (rule in msgTranslations) { - if (exports.rules.hasOwnProperty(rule)) { - exports.rules[rule].message = msgTranslations[rule]; - } - } - }; - //#endregion - - //#region ApplyBindings Added Functionality - ko.applyBindingsWithValidation = function (viewModel, rootNode, options) { - var len = arguments.length, - node, config; - - if (len > 2) { // all parameters were passed - node = rootNode; - config = options; - } else if (len < 2) { - node = document.body; - } else { //have to figure out if they passed in a root node or options - if (arguments[1].nodeType) { //its a node - node = rootNode; - } else { - config = arguments[1]; - } - } - - exports.init(); - - if (config) { exports.utils.setDomData(node, config); } - - ko.applyBindings(viewModel, rootNode); - }; - - //override the original applyBindings so that we can ensure all new rules and what not are correctly registered - var origApplyBindings = ko.applyBindings; - ko.applyBindings = function (viewModel, rootNode) { - - exports.init(); - - origApplyBindings(viewModel, rootNode); - }; - - //#endregion -})); + ko.validation = exports;;/*global ko: false*/ + +var defaults = { + registerExtenders: true, + messagesOnModified: true, + errorsAsTitle: true, // enables/disables showing of errors as title attribute of the target element. + errorsAsTitleOnModified: false, // shows the error when hovering the input field (decorateElement must be true) + messageTemplate: null, + insertMessages: true, // automatically inserts validation messages as + parseInputAttributes: false, // parses the HTML5 validation attribute from a form element and adds that to the object + writeInputAttributes: false, // adds HTML5 input validation attributes to form elements that ko observable's are bound to + decorateElement: false, // false to keep backward compatibility + decorateElementOnModified: true,// true to keep backward compatibility + errorClass: null, // single class for error message and element + errorElementClass: 'validationElement', // class to decorate error element + errorMessageClass: 'validationMessage', // class to decorate error message + grouping: { + deep: false, //by default grouping is shallow + observable: true //and using observables + } +}; + +// make a copy so we can use 'reset' later +var configuration = ko.utils.extend({}, defaults); + +configuration.html5Attributes = ['required', 'pattern', 'min', 'max', 'step']; +configuration.html5InputTypes = ['email', 'number', 'date']; + +configuration.reset = function () { + ko.utils.extend(configuration, defaults); +}; + +ko.validation.configuration = configuration;;ko.validation.utils = (function () { + var seedId = new Date().getTime(); + + var domData = {}; //hash of data objects that we reference from dom elements + var domDataKey = '__ko_validation__'; + + return { + isArray: function (o) { + return o.isArray || Object.prototype.toString.call(o) === '[object Array]'; + }, + isObject: function (o) { + return o !== null && typeof o === 'object'; + }, + values: function (o) { + var r = []; + for (var i in o) { + if (o.hasOwnProperty(i)) { + r.push(o[i]); + } + } + return r; + }, + getValue: function (o) { + return (typeof o === 'function' ? o() : o); + }, + hasAttribute: function (node, attr) { + return node.getAttribute(attr) !== null; + }, + getAttribute: function (element, attr) { + return element.getAttribute(attr); + }, + setAttribute: function (element, attr, value) { + return element.setAttribute(attr, value); + }, + isValidatable: function (o) { + return o && o.rules && o.isValid && o.isModified; + }, + insertAfter: function (node, newNode) { + node.parentNode.insertBefore(newNode, node.nextSibling); + }, + newId: function () { + return seedId += 1; + }, + getConfigOptions: function (element) { + var options = ko.validation.utils.contextFor(element); + + return options || ko.validation.configuration; + }, + setDomData: function (node, data) { + var key = node[domDataKey]; + + if (!key) { + node[domDataKey] = key = ko.validation.utils.newId(); + } + + domData[key] = data; + }, + getDomData: function (node) { + var key = node[domDataKey]; + + if (!key) { + return undefined; + } + + return domData[key]; + }, + contextFor: function (node) { + switch (node.nodeType) { + case 1: + case 8: + var context = ko.validation.utils.getDomData(node); + if (context) { return context; } + if (node.parentNode) { return ko.validation.utils.contextFor(node.parentNode); } + break; + } + return undefined; + }, + isEmptyVal: function (val) { + if (val === undefined) { + return true; + } + if (val === null) { + return true; + } + if (val === "") { + return true; + } + }, + getOriginalElementTitle: function (element) { + var savedOriginalTitle = ko.validation.utils.getAttribute(element, 'data-orig-title'), + currentTitle = element.title, + hasSavedOriginalTitle = ko.validation.utils.hasAttribute(element, 'data-orig-title'); + + return hasSavedOriginalTitle ? + savedOriginalTitle : currentTitle; + }, + async: function (expr) { + if (window.setImmediate) { window.setImmediate(expr); } + else { window.setTimeout(expr, 0); } + } + }; +}());;var api = (function () { + + var isInitialized = 0, + configuration = ko.validation.configuration, + utils = ko.validation.utils; + + return { + //Call this on startup + //any config can be overridden with the passed in options + init: function (options, force) { + //done run this multiple times if we don't really want to + if (isInitialized > 0 && !force) { + return; + } + + //becuase we will be accessing options properties it has to be an object at least + options = options || {}; + //if specific error classes are not provided then apply generic errorClass + //it has to be done on option so that options.errorClass can override default + //errorElementClass and errorMessage class but not those provided in options + options.errorElementClass = options.errorElementClass || options.errorClass || configuration.errorElementClass; + options.errorMessageClass = options.errorMessageClass || options.errorClass || configuration.errorMessageClass; + + ko.utils.extend(configuration, options); + + if (configuration.registerExtenders) { + ko.validation.registerExtenders(); + } + + isInitialized = 1; + }, + // backwards compatability + configure: function (options) { ko.validation.init(options); }, + + // resets the config back to its original state + reset: ko.validation.configuration.reset, + + // recursivly walks a viewModel and creates an object that + // provides validation information for the entire viewModel + // obj -> the viewModel to walk + // options -> { + // deep: false, // if true, will walk past the first level of viewModel properties + // observable: false // if true, returns a computed observable indicating if the viewModel is valid + // } + group: function group(obj, options) { // array of observables or viewModel + options = ko.utils.extend(ko.utils.extend({}, configuration.grouping), options); + + var validatables = ko.observableArray([]), + result = null, + + //anonymous, immediate function to traverse objects hierarchically + //if !options.deep then it will stop on top level + traverse = function traverse(obj, level) { + var objValues = [], + val = ko.utils.unwrapObservable(obj); + + //default level value depends on deep option. + level = (level !== undefined ? level : options.deep ? 1 : -1); + + // if object is observable then add it to the list + if (ko.isObservable(obj)) { + + //make sure it is validatable object + if (!obj.isValid) { obj.extend({ validatable: true }); } + validatables.push(obj); + } + + //get list of values either from array or object but ignore non-objects + if (val) { + if (utils.isArray(val)) { + objValues = val; + } else if (utils.isObject(val)) { + objValues = utils.values(val); + } + } + + //process recurisvely if it is deep grouping + if (level !== 0) { + ko.utils.arrayForEach(objValues, function (observable) { + + //but not falsy things and not HTML Elements + if (observable && !observable.nodeType) { traverse(observable, level + 1); } + }); + } + }; + + //if using observables then traverse structure once and add observables + if (options.observable) { + + traverse(obj); + + result = ko.computed(function () { + var errors = []; + ko.utils.arrayForEach(validatables(), function (observable) { + if (!observable.isValid()) { + errors.push(observable.error); + } + }); + return errors; + }); + + } else { //if not using observables then every call to error() should traverse the structure + result = function () { + var errors = []; + validatables([]); //clear validatables + traverse(obj); // and traverse tree again + ko.utils.arrayForEach(validatables(), function (observable) { + if (!observable.isValid()) { + errors.push(observable.error); + } + }); + return errors; + }; + + + } + + result.showAllMessages = function (show) { // thanks @heliosPortal + if (show === undefined) {//default to true + show = true; + } + + // ensure we have latest changes + result(); + + ko.utils.arrayForEach(validatables(), function (observable) { + observable.isModified(show); + }); + }; + + obj.errors = result; + obj.isValid = function () { + return obj.errors().length === 0; + }; + obj.isAnyMessageShown = function () { + var invalidAndModifiedPresent = false; + + // ensure we have latest changes + result(); + + ko.utils.arrayForEach(validatables(), function (observable) { + if (!observable.isValid() && observable.isModified()) { + invalidAndModifiedPresent = true; + } + }); + return invalidAndModifiedPresent; + }; + + return result; + }, + + formatMessage: function (message, params) { + if (typeof (message) === 'function') { + return message(params); + } + return message.replace(/\{0\}/gi, ko.utils.unwrapObservable(params)); + }, + + // addRule: + // This takes in a ko.observable and a Rule Context - which is just a rule name and params to supply to the validator + // ie: ko.validation.addRule(myObservable, { + // rule: 'required', + // params: true + // }); + // + addRule: function (observable, rule) { + observable.extend({ validatable: true }); + + //push a Rule Context to the observables local array of Rule Contexts + observable.rules.push(rule); + return observable; + }, + + // addAnonymousRule: + // Anonymous Rules essentially have all the properties of a Rule, but are only specific for a certain property + // and developers typically are wanting to add them on the fly or not register a rule with the 'ko.validation.rules' object + // + // Example: + // var test = ko.observable('something').extend{( + // validation: { + // validator: function(val, someOtherVal){ + // return true; + // }, + // message: "Something must be really wrong!', + // params: true + // } + // )}; + addAnonymousRule: function (observable, ruleObj) { + var ruleName = utils.newId(); + + if (ruleObj['message'] === undefined) { + ruleObj['message'] = 'Error'; + } + + //Create an anonymous rule to reference + ko.validation.rules[ruleName] = ruleObj; + + //add the anonymous rule to the observable + ko.validation.addRule(observable, { + rule: ruleName, + params: ruleObj.params + }); + }, + + addExtender: function (ruleName) { + ko.extenders[ruleName] = function (observable, params) { + //params can come in a few flavors + // 1. Just the params to be passed to the validator + // 2. An object containing the Message to be used and the Params to pass to the validator + // 3. A condition when the validation rule to be applied + // + // Example: + // var test = ko.observable(3).extend({ + // max: { + // message: 'This special field has a Max of {0}', + // params: 2, + // onlyIf: function() { + // return specialField.IsVisible(); + // } + // } + // )}; + // + if (params.message || params.onlyIf) { //if it has a message or condition object, then its an object literal to use + return ko.validation.addRule(observable, { + rule: ruleName, + message: params.message, + params: utils.isEmptyVal(params.params) ? true : params.params, + condition: params.onlyIf + }); + } else { + return ko.validation.addRule(observable, { + rule: ruleName, + params: params + }); + } + }; + }, + + // loops through all ko.validation.rules and adds them as extenders to + // ko.extenders + registerExtenders: function () { // root extenders optional, use 'validation' extender if would cause conflicts + if (configuration.registerExtenders) { + for (var ruleName in ko.validation.rules) { + if (ko.validation.rules.hasOwnProperty(ruleName)) { + if (!ko.extenders[ruleName]) { + ko.validation.addExtender(ruleName); + } + } + } + } + }, + + //creates a span next to the @element with the specified error class + insertValidationMessage: function (element) { + var span = document.createElement('SPAN'); + span.className = utils.getConfigOptions(element).errorMessageClass; + utils.insertAfter(element, span); + return span; + }, + + // if html-5 validation attributes have been specified, this parses + // the attributes on @element + parseInputValidationAttributes: function (element, valueAccessor) { + ko.utils.arrayForEach(ko.validation.configuration.html5Attributes, function (attr) { + if (utils.hasAttribute(element, attr)) { + ko.validation.addRule(valueAccessor(), { + rule: attr, + params: element.getAttribute(attr) || true + }); + } + }); + + var currentType = element.getAttribute('type'); + ko.utils.arrayForEach(ko.validation.configuration.html5InputTypes, function (type) { + if (type === currentType) { + ko.validation.addRule(valueAccessor(), { + rule: (type === 'date') ? 'dateISO' : type, + params: true + }); + } + }); + }, + + // writes html5 validation attributes on the element passed in + writeInputValidationAttributes: function (element, valueAccessor) { + var observable = valueAccessor(); + + if (!observable || !observable.rules) { + return; + } + + var contexts = observable.rules(); // observable array + + // loop through the attributes and add the information needed + ko.utils.arrayForEach(ko.validation.configuration.html5Attributes, function (attr) { + var params; + var ctx = ko.utils.arrayFirst(contexts, function (ctx) { + return ctx.rule.toLowerCase() === attr.toLowerCase(); + }); + + if (!ctx) { + return; + } + + params = ctx.params; + + // we have to do some special things for the pattern validation + if (ctx.rule === "pattern") { + if (ctx.params instanceof RegExp) { + params = ctx.params.source; // we need the pure string representation of the RegExpr without the //gi stuff + } + } + + // we have a rule matching a validation attribute at this point + // so lets add it to the element along with the params + element.setAttribute(attr, params); + }); + + contexts = null; + }, + + //take an existing binding handler and make it cause automatic validations + makeBindingHandlerValidatable: function (handlerName) { + var init = ko.bindingHandlers[handlerName].init; + + ko.bindingHandlers[handlerName].init = function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + + init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext); + + return ko.bindingHandlers['validationCore'].init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext); + }; + } + }; +}()); + +// expose api publicly +ko.utils.extend(ko.validation, api);;//Validation Rules: +// You can view and override messages or rules via: +// ko.validation.rules[ruleName] +// +// To implement a custom Rule, simply use this template: +// ko.validation.rules[''] = { +// validator: function (val, param) { +// +// return ; +// }, +// message: '' //optionally you can also use a '{0}' to denote a placeholder that will be replaced with your 'param' +// }; +// +// Example: +// ko.validation.rules['mustEqual'] = { +// validator: function( val, mustEqualVal ){ +// return val === mustEqualVal; +// }, +// message: 'This field must equal {0}' +// }; +// +ko.validation.rules = {}; +ko.validation.rules['required'] = { + validator: function (val, required) { + var stringTrimRegEx = /^\s+|\s+$/g, + testVal; + + if (val === undefined || val === null) { + return !required; + } + + testVal = val; + if (typeof (val) === "string") { + testVal = val.replace(stringTrimRegEx, ''); + } + + if (!required) {// if they passed: { required: false }, then don't require this + return true; + } + + return ((testVal + '').length > 0); + }, + message: 'This field is required.' +}; + +ko.validation.rules['min'] = { + validator: function (val, min) { + return ko.validation.utils.isEmptyVal(val) || val >= min; + }, + message: 'Please enter a value greater than or equal to {0}.' +}; + +ko.validation.rules['max'] = { + validator: function (val, max) { + return ko.validation.utils.isEmptyVal(val) || val <= max; + }, + message: 'Please enter a value less than or equal to {0}.' +}; + +ko.validation.rules['minLength'] = { + validator: function (val, minLength) { + return ko.validation.utils.isEmptyVal(val) || val.length >= minLength; + }, + message: 'Please enter at least {0} characters.' +}; + +ko.validation.rules['maxLength'] = { + validator: function (val, maxLength) { + return ko.validation.utils.isEmptyVal(val) || val.length <= maxLength; + }, + message: 'Please enter no more than {0} characters.' +}; + +ko.validation.rules['pattern'] = { + validator: function (val, regex) { + return ko.validation.utils.isEmptyVal(val) || val.toString().match(regex) !== null; + }, + message: 'Please check this value.' +}; + +ko.validation.rules['step'] = { + validator: function (val, step) { + + // 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 (ko.validation.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; + }, + message: 'The value must increment by {0}' +}; + +ko.validation.rules['email'] = { + validator: function (val, validate) { + if (!validate) { return true; } + + //I think an empty email address is also a valid entry + //if one want's to enforce entry it should be done with 'required: true' + return ko.validation.utils.isEmptyVal(val) || ( + // jquery validate regex - thanks Scott Gonzalez + validate && /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(val) + ); + }, + message: 'Please enter a proper email address' +}; + +ko.validation.rules['date'] = { + validator: function (value, validate) { + if (!validate) { return true; } + return ko.validation.utils.isEmptyVal(value) || (validate && !/Invalid|NaN/.test(new Date(value))); + }, + message: 'Please enter a proper date' +}; + +ko.validation.rules['dateISO'] = { + validator: function (value, validate) { + if (!validate) { return true; } + return ko.validation.utils.isEmptyVal(value) || (validate && /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(value)); + }, + message: 'Please enter a proper date' +}; + +ko.validation.rules['number'] = { + validator: function (value, validate) { + if (!validate) { return true; } + return ko.validation.utils.isEmptyVal(value) || (validate && /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value)); + }, + message: 'Please enter a number' +}; + +ko.validation.rules['digit'] = { + validator: function (value, validate) { + if (!validate) { return true; } + return ko.validation.utils.isEmptyVal(value) || (validate && /^\d+$/.test(value)); + }, + message: 'Please enter a digit' +}; + +ko.validation.rules['phoneUS'] = { + validator: function (phoneNumber, validate) { + if (!validate) { return true; } + if (typeof (phoneNumber) !== 'string') { return false; } + if (ko.validation.utils.isEmptyVal(phoneNumber)) { return true; } // makes it optional, use 'required' rule if it should be required + phoneNumber = phoneNumber.replace(/\s+/g, ""); + return validate && phoneNumber.length > 9 && phoneNumber.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/); + }, + message: 'Please specify a valid phone number' +}; + +ko.validation.rules['equal'] = { + validator: function (val, params) { + var otherValue = params; + return val === ko.validation.utils.getValue(otherValue); + }, + message: 'Values must equal' +}; + +ko.validation.rules['notEqual'] = { + validator: function (val, params) { + var otherValue = params; + return val !== ko.validation.utils.getValue(otherValue); + }, + message: 'Please choose another value.' +}; + +//unique in collection +// options are: +// collection: array or function returning (observable) array +// in which the value has to be unique +// valueAccessor: function that returns value from an object stored in collection +// if it is null the value is compared directly +// external: set to true when object you are validating is automatically updating collection +ko.validation.rules['unique'] = { + validator: function (val, options) { + var c = ko.validation.utils.getValue(options.collection), + external = ko.validation.utils.getValue(options.externalValue), + counter = 0; + + if (!val || !c) { return true; } + + ko.utils.arrayFilter(ko.utils.unwrapObservable(c), function (item) { + if (val === (options.valueAccessor ? options.valueAccessor(item) : item)) { counter++; } + }); + // if value is external even 1 same value in collection means the value is not unique + return counter < (external !== undefined && val !== external ? 1 : 2); + }, + message: 'Please make sure the value is unique.' +}; + + +//now register all of these! +(function () { + ko.validation.registerExtenders(); +}()); +;// The core binding handler +// this allows us to setup any value binding that internally always +// performs the same functionality +ko.bindingHandlers['validationCore'] = (function () { + + return { + init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + var config = ko.validation.utils.getConfigOptions(element); + + // parse html5 input validation attributes, optional feature + if (config.parseInputAttributes) { + ko.validation.utils.async(function () { ko.validation.parseInputValidationAttributes(element, valueAccessor); }); + } + + // if requested insert message element and apply bindings + if (config.insertMessages && ko.validation.utils.isValidatable(valueAccessor())) { + + // insert the + var validationMessageElement = ko.validation.insertValidationMessage(element); + + // if we're told to use a template, make sure that gets rendered + if (config.messageTemplate) { + ko.renderTemplate(config.messageTemplate, { field: valueAccessor() }, null, validationMessageElement, 'replaceNode'); + } else { + ko.applyBindingsToNode(validationMessageElement, { validationMessage: valueAccessor() }); + } + } + + // write the html5 attributes if indicated by the config + if (config.writeInputAttributes && ko.validation.utils.isValidatable(valueAccessor())) { + + ko.validation.writeInputValidationAttributes(element, valueAccessor); + } + + // if requested, add binding to decorate element + if (config.decorateElement && ko.validation.utils.isValidatable(valueAccessor())) { + ko.applyBindingsToNode(element, { validationElement: valueAccessor() }); + } + }, + + update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + // hook for future extensibility + } + }; + +}()); + +// override for KO's default 'value' and 'checked' bindings +ko.validation.makeBindingHandlerValidatable("value"); +ko.validation.makeBindingHandlerValidatable("checked"); + + +ko.bindingHandlers['validationMessage'] = { // individual error message, if modified or post binding + update: function (element, valueAccessor) { + var obsv = valueAccessor(), + config = ko.validation.utils.getConfigOptions(element), + val = ko.utils.unwrapObservable(obsv), + msg = null, + isModified = false, + isValid = false; + + obsv.extend({ validatable: true }); + + isModified = obsv.isModified(); + isValid = obsv.isValid(); + + // create a handler to correctly return an error message + var errorMsgAccessor = function () { + if (!config.messagesOnModified || isModified) { + return isValid ? null : obsv.error; + } else { + return null; + } + }; + + //toggle visibility on validation messages when validation hasn't been evaluated, or when the object isValid + var visiblityAccessor = function () { + return (!config.messagesOnModified || isModified) ? !isValid : false; + }; + + ko.bindingHandlers.text.update(element, errorMsgAccessor); + ko.bindingHandlers.visible.update(element, visiblityAccessor); + } +}; + +ko.bindingHandlers['validationElement'] = { + update: function (element, valueAccessor) { + var obsv = valueAccessor(), + config = ko.validation.utils.getConfigOptions(element), + val = ko.utils.unwrapObservable(obsv), + msg = null, + isModified = false, + isValid = false; + + obsv.extend({ validatable: true }); + + isModified = obsv.isModified(); + isValid = obsv.isValid(); + + // create an evaluator function that will return something like: + // css: { validationElement: true } + var cssSettingsAccessor = function () { + var css = {}; + + var shouldShow = ((!config.decorateElementOnModified || isModified) ? !isValid : false); + + if (!config.decorateElement) { shouldShow = false; } + + // css: { validationElement: false } + css[config.errorElementClass] = shouldShow; + + return css; + }; + + //add or remove class on the element; + ko.bindingHandlers.css.update(element, cssSettingsAccessor); + if (!config.errorsAsTitle) { return; } + + var origTitle = ko.validation.utils.getAttribute(element, 'data-orig-title'), + elementTitle = element.title, + titleIsErrorMsg = ko.validation.utils.getAttribute(element, 'data-orig-title') === "true"; + + var errorMsgTitleAccessor = function () { + if (!config.errorsAsTitleOnModified || isModified) { + if (!isValid) { + return { title: obsv.error, 'data-orig-title': ko.validation.utils.getOriginalElementTitle(element) }; + } else { + return { title: ko.validation.utils.getOriginalElementTitle(element), 'data-orig-title': null }; + } + } + }; + ko.bindingHandlers.attr.update(element, errorMsgTitleAccessor); + } +}; + +// ValidationOptions: +// This binding handler allows you to override the initial config by setting any of the options for a specific element or context of elements +// +// Example: +//
+// +// +//
+ko.bindingHandlers['validationOptions'] = (function () { + return { + init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + var options = ko.utils.unwrapObservable(valueAccessor()); + if (options) { + var newConfig = ko.utils.extend({}, ko.validation.configuration); + ko.utils.extend(newConfig, options); + + //store the validation options on the node so we can retrieve it later + ko.validation.utils.setDomData(element, newConfig); + } + } + }; +}()); +;// Validation Extender: +// This is for creating custom validation logic on the fly +// Example: +// var test = ko.observable('something').extend{( +// validation: { +// validator: function(val, someOtherVal){ +// return true; +// }, +// message: "Something must be really wrong!', +// params: true +// } +// )}; +ko.extenders['validation'] = function (observable, rules) { // allow single rule or array + ko.utils.arrayForEach(ko.validation.utils.isArray(rules) ? rules : [rules], function (rule) { + // the 'rule' being passed in here has no name to identify a core Rule, + // so we add it as an anonymous rule + // If the developer is wanting to use a core Rule, but use a different message see the 'addExtender' logic for examples + ko.validation.addAnonymousRule(observable, rule); + }); + return observable; +}; + +//This is the extender that makes a Knockout Observable also 'Validatable' +//examples include: +// 1. var test = ko.observable('something').extend({validatable: true}); +// this will ensure that the Observable object is setup properly to respond to rules +// +// 2. test.extend({validatable: false}); +// this will remove the validation properties from the Observable object should you need to do that. +ko.extenders['validatable'] = function (observable, enable) { + if (enable && !ko.validation.utils.isValidatable(observable)) { + + observable.error = ko.observable(null); // holds the error message, we only need one since we stop processing validators when one is invalid + + // observable.rules: + // ObservableArray of Rule Contexts, where a Rule Context is simply the name of a rule and the params to supply to it + // + // Rule Context = { rule: '', params: '', message: '' } + observable.rules = ko.observableArray(); //holds the rule Contexts to use as part of validation + + //in case async validation is occuring + observable.isValidating = ko.observable(false); + + //the true holder of whether the observable is valid or not + observable.__valid__ = ko.observable(true); + + observable.isModified = ko.observable(false); + + // we use a computed here to ensure that anytime a dependency changes, the + // validation logic evaluates + var h_obsValidationTrigger = ko.computed(function () { + var obs = observable(), + ruleContexts = observable.rules(); + + ko.validation.validateObservable(observable); + + return true; + }); + + // a semi-protected observable + observable.isValid = ko.computed(function () { + return observable.__valid__(); + }); + + //manually set error state + observable.setError = function (error) { + observable.error(error); + observable.__valid__(false); + }; + + //manually clear error state + observable.clearError = function () { + observable.error(null); + observable.__valid__(true); + }; + + //subscribe to changes in the observable + var h_change = observable.subscribe(function () { + observable.isModified(true); + }); + + observable._disposeValidation = function () { + //first dispose of the subscriptions + observable.isValid.dispose(); + observable.rules.removeAll(); + observable.isModified._subscriptions['change'] = []; + observable.isValidating._subscriptions['change'] = []; + observable.__valid__._subscriptions['change'] = []; + h_change.dispose(); + h_obsValidationTrigger.dispose(); + + delete observable['rules']; + delete observable['error']; + delete observable['isValid']; + delete observable['isValidating']; + delete observable['__valid__']; + delete observable['isModified']; + }; + } else if (enable === false && ko.validation.utils.isValidatable(observable)) { + + if (observable._disposeValidation) { + observable._disposeValidation(); + } + } + return observable; +}; + +function validateSync(observable, rule, ctx) { + //Execute the validator and see if its valid + if (!rule.validator(observable(), ctx.params === undefined ? true : ctx.params)) { // default param is true, eg. required = true + + //not valid, so format the error message and stick it in the 'error' variable + observable.error(ko.validation.formatMessage(ctx.message || rule.message, ctx.params)); + observable.__valid__(false); + return false; + } else { + return true; + } +} + +function validateAsync(observable, rule, ctx) { + observable.isValidating(true); + + var callBack = function (valObj) { + var isValid = false, + msg = ''; + + if (!observable.__valid__()) { + + // since we're returning early, make sure we turn this off + observable.isValidating(false); + + return; //if its already NOT valid, don't add to that + } + + //we were handed back a complex object + if (valObj['message']) { + isValid = valObj.isValid; + msg = valObj.message; + } else { + isValid = valObj; + } + + if (!isValid) { + //not valid, so format the error message and stick it in the 'error' variable + observable.error(ko.validation.formatMessage(msg || ctx.message || rule.message, ctx.params)); + observable.__valid__(isValid); + } + + // tell it that we're done + observable.isValidating(false); + }; + + //fire the validator and hand it the callback + rule.validator(observable(), ctx.params || true, callBack); +} + +ko.validation.validateObservable = function (observable) { + var i = 0, + rule, // the rule validator to execute + ctx, // the current Rule Context for the loop + ruleContexts = observable.rules(), //cache for iterator + len = ruleContexts.length; //cache for iterator + + for (; i < len; i++) { + + //get the Rule Context info to give to the core Rule + ctx = ruleContexts[i]; + + // checks an 'onlyIf' condition + if (ctx.condition && !ctx.condition()) { + continue; + } + + //get the core Rule to use for validation + rule = ko.validation.rules[ctx.rule]; + + if (rule['async'] || ctx['async']) { + //run async validation + validateAsync(observable, rule, ctx); + + } else { + //run normal sync validation + if (!validateSync(observable, rule, ctx)) { + return false; //break out of the loop + } + } + } + //finally if we got this far, make the observable valid again! + observable.error(null); + observable.__valid__(true); + return true; +};; +//quick function to override rule messages +ko.validation.localize = function (msgTranslations) { + + var msg, rule; + + //loop the properties in the object and assign the msg to the rule + for (rule in msgTranslations) { + if (ko.validation.rules.hasOwnProperty(rule)) { + ko.validation.rules[rule].message = msgTranslations[rule]; + } + } +};;ko.applyBindingsWithValidation = function (viewModel, rootNode, options) { + var len = arguments.length, + node, config; + + if (len > 2) { // all parameters were passed + node = rootNode; + config = options; + } else if (len < 2) { + node = document.body; + } else { //have to figure out if they passed in a root node or options + if (arguments[1].nodeType) { //its a node + node = rootNode; + } else { + config = arguments[1]; + } + } + + ko.validation.init(); + + if (config) { ko.validation.utils.setDomData(node, config); } + + ko.applyBindings(viewModel, rootNode); +}; + +//override the original applyBindings so that we can ensure all new rules and what not are correctly registered +var origApplyBindings = ko.applyBindings; +ko.applyBindings = function (viewModel, rootNode) { + + ko.validation.init(); + + origApplyBindings(viewModel, rootNode); +}; + +ko.validatedObservable = function (initialValue) { + if (!ko.validation.utils.isObject(initialValue)) { return ko.observable(initialValue).extend({ validatable: true }); } + + var obsv = ko.observable(initialValue); + obsv.errors = ko.validation.group(initialValue); + obsv.isValid = ko.computed(function () { + return obsv.errors().length === 0; + }); + + return obsv; +};;})); \ No newline at end of file diff --git a/Dist/knockout.validation.min.js b/Dist/knockout.validation.min.js index e3de8d95..da44a3b9 100644 --- a/Dist/knockout.validation.min.js +++ b/Dist/knockout.validation.min.js @@ -1,8 +1,2 @@ -/*============================================================================= - Author: Eric M. Barnard - @ericmbarnard - License: MIT (http://opensource.org/licenses/mit-license.php) - - Description: Validation Library for KnockoutJS -=============================================================================== -*/ -!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a,c,d){return c.validator(a(),void 0===d.params?!0:d.params)?!0:(a.error(b.formatMessage(d.message||c.message,d.params)),a.__valid__(!1),!1)}function d(a,c,d){a.isValidating(!0);var e=function(e){var f=!1,g="";return a.__valid__()?(e.message?(f=e.isValid,g=e.message):f=e,f||(a.error(b.formatMessage(g||d.message||c.message,d.params)),a.__valid__(f)),a.isValidating(!1),void 0):(a.isValidating(!1),void 0)};c.validator(a(),d.params||!0,e)}if(void 0===typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";var e=b;a.validation=e;var f={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateElement:!1,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",grouping:{deep:!1,observable:!0}},g=a.utils.extend({},f),h=["required","pattern","min","max","step"],i=["email","number","date"],j=function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},k=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return a&&a.rules&&a.isValid&&a.isModified},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=k.contextFor(a);return b||g},setDomData:function(a,d){var e=a[c];e||(a[c]=e=k.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=k.getDomData(a);if(b)return b;if(a.parentNode)return k.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=k.getAttribute(a,"data-orig-title"),c=a.title,d=k.hasAttribute(a,"data-orig-title");return d?b:c}}}(),l=function(){var c=0;return{utils:k,init:function(d,e){c>0&&!e||(d=d||{},d.errorElementClass=d.errorElementClass||d.errorClass||g.errorElementClass,d.errorMessageClass=d.errorMessageClass||d.errorClass||g.errorMessageClass,a.utils.extend(g,d),g.registerExtenders&&b.registerExtenders(),c=1)},configure:function(a){b.init(a)},reset:function(){g=jQuery.extend(g,f)},group:function(b,c){c=a.utils.extend(a.utils.extend({},g.grouping),c);var d=a.observableArray([]),e=null,f=function h(b,e){var f=[],g=a.utils.unwrapObservable(b);e=void 0!==e?e:c.deep?1:-1,a.isObservable(b)&&(b.isValid||b.extend({validatable:!0}),d.push(b)),g&&(k.isArray(g)?f=g:k.isObject(g)&&(f=k.values(g))),0!==e&&a.utils.arrayForEach(f,function(a){a&&!a.nodeType&&h(a,e+1)})};return c.observable?(f(b),e=a.computed(function(){var b=[];return a.utils.arrayForEach(d(),function(a){a.isValid()||b.push(a.error)}),b})):e=function(){var c=[];return d([]),f(b),a.utils.arrayForEach(d(),function(a){a.isValid()||c.push(a.error)}),c},e.showAllMessages=function(b){void 0===b&&(b=!0),e(),a.utils.arrayForEach(d(),function(a){a.isModified(b)})},b.errors=e,b.isValid=function(){return 0===b.errors().length},b.isAnyMessageShown=function(){var b=!1;return e(),a.utils.arrayForEach(d(),function(a){!a.isValid()&&a.isModified()&&(b=!0)}),b},e},formatMessage:function(b,c){return"function"==typeof b?b(c):b.replace(/\{0\}/gi,a.utils.unwrapObservable(c))},addRule:function(a,b){return a.extend({validatable:!0}),a.rules.push(b),a},addAnonymousRule:function(a,c){var d=k.newId();void 0===c.message&&(c.message="Error"),b.rules[d]=c,b.addRule(a,{rule:d,params:c.params})},addExtender:function(c){a.extenders[c]=function(a,d){return d.message||d.onlyIf?b.addRule(a,{rule:c,message:d.message,params:k.isEmptyVal(d.params)?!0:d.params,condition:d.onlyIf}):b.addRule(a,{rule:c,params:d})}},registerExtenders:function(){if(g.registerExtenders)for(var c in b.rules)b.rules.hasOwnProperty(c)&&(a.extenders[c]||b.addExtender(c))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=k.getConfigOptions(a).errorMessageClass,k.insertAfter(a,b),b},parseInputValidationAttributes:function(c,d){a.utils.arrayForEach(h,function(a){k.hasAttribute(c,a)&&b.addRule(d(),{rule:a,params:c.getAttribute(a)||!0})});var e=c.getAttribute("type");a.utils.arrayForEach(i,function(a){a===e&&b.addRule(d(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(b,c){var d=c();if(d&&d.rules){var e=d.rules();a.utils.arrayForEach(h,function(c){var d,f=a.utils.arrayFirst(e,function(a){return a.rule.toLowerCase()===c.toLowerCase()});f&&(d=f.params,"pattern"===f.rule&&f.params instanceof RegExp&&(d=f.params.source),b.setAttribute(c,d))}),e=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e),a.bindingHandlers.validationCore.init(b,d,e,f,g)}}}}();a.utils.extend(e,l),e.rules={},e.rules.required={validator:function(a,b){var c,d=/^\s+|\s+$/g;return void 0===a||null===a?!b:(c=a,"string"==typeof a&&(c=a.replace(d,"")),b?(c+"").length>0:!0)},message:"This field is required."},e.rules.min={validator:function(a,b){return k.isEmptyVal(a)||a>=b},message:"Please enter a value greater than or equal to {0}."},e.rules.max={validator:function(a,b){return k.isEmptyVal(a)||b>=a},message:"Please enter a value less than or equal to {0}."},e.rules.minLength={validator:function(a,b){return k.isEmptyVal(a)||a.length>=b},message:"Please enter at least {0} characters."},e.rules.maxLength={validator:function(a,b){return k.isEmptyVal(a)||a.length<=b},message:"Please enter no more than {0} characters."},e.rules.pattern={validator:function(a,b){return k.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},e.rules.step={validator:function(a,b){return k.isEmptyVal(a)||0===100*a%(100*b)},message:"The value must increment by {0}"},e.rules.email={validator:function(a,b){return b?k.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address"},e.rules.date={validator:function(a,b){return b?k.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date"},e.rules.dateISO={validator:function(a,b){return b?k.isEmptyVal(a)||b&&/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(a):!0},message:"Please enter a proper date"},e.rules.number={validator:function(a,b){return b?k.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(a):!0},message:"Please enter a number"},e.rules.digit={validator:function(a,b){return b?k.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit"},e.rules.phoneUS={validator:function(a,b){return b?"string"!=typeof a?!1:k.isEmptyVal(a)?!0:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number"},e.rules.equal={validator:function(a,b){var c=b;return a===k.getValue(c)},message:"Values must equal"},e.rules.notEqual={validator:function(a,b){var c=b;return a!==k.getValue(c)},message:"Please choose another value."},e.rules.unique={validator:function(b,c){var d=k.getValue(c.collection),e=k.getValue(c.externalValue),f=0;return b&&d?(a.utils.arrayFilter(a.utils.unwrapObservable(d),function(a){b===(c.valueAccessor?c.valueAccessor(a):a)&&f++}),(void 0!==e&&b!==e?1:2)>f):!0},message:"Please make sure the value is unique."},function(){e.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(c,d){var e=k.getConfigOptions(c);if(e.parseInputAttributes&&j(function(){b.parseInputValidationAttributes(c,d)}),e.insertMessages&&k.isValidatable(d())){var f=b.insertValidationMessage(c);e.messageTemplate?a.renderTemplate(e.messageTemplate,{field:d()},null,f,"replaceNode"):a.applyBindingsToNode(f,{validationMessage:d()})}e.writeInputAttributes&&k.isValidatable(d())&&b.writeInputValidationAttributes(c,d),e.decorateElement&&k.isValidatable(d())&&a.applyBindingsToNode(c,{validationElement:d()})},update:function(){}}}(),l.makeBindingHandlerValidatable("value"),l.makeBindingHandlerValidatable("checked"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=k.getConfigOptions(b),f=(a.utils.unwrapObservable(d),!1),g=!1;d.extend({validatable:!0}),f=d.isModified(),g=d.isValid();var h=function(){return!e.messagesOnModified||f?g?null:d.error:null},i=function(){return!e.messagesOnModified||f?!g:!1};a.bindingHandlers.text.update(b,h),a.bindingHandlers.visible.update(b,i)}},a.bindingHandlers.validationElement={update:function(b,c){var d=c(),e=k.getConfigOptions(b),f=(a.utils.unwrapObservable(d),!1),g=!1;d.extend({validatable:!0}),f=d.isModified(),g=d.isValid();var h=function(){var a={},b=f?!g:!1;return e.decorateElement||(b=!1),a[e.errorElementClass]=b,a};if(a.bindingHandlers.css.update(b,h),e.errorsAsTitle){k.getAttribute(b,"data-orig-title"),b.title,"true"===k.getAttribute(b,"data-orig-title");var i=function(){return!e.errorsAsTitleOnModified||f?g?{title:k.getOriginalElementTitle(b),"data-orig-title":null}:{title:d.error,"data-orig-title":k.getOriginalElementTitle(b)}:void 0};a.bindingHandlers.attr.update(b,i)}}},a.bindingHandlers.validationOptions=function(){return{init:function(b,c){var d=a.utils.unwrapObservable(c());if(d){var e=a.utils.extend({},g);a.utils.extend(e,d),k.setDomData(b,e)}}}}(),a.extenders.validation=function(c,d){return a.utils.arrayForEach(k.isArray(d)?d:[d],function(a){b.addAnonymousRule(c,a)}),c},a.extenders.validatable=function(c,d){if(d&&!k.isValidatable(c)){c.error=a.observable(null),c.rules=a.observableArray(),c.isValidating=a.observable(!1),c.__valid__=a.observable(!0),c.isModified=a.observable(!1);var e=a.computed(function(){return c(),c.rules(),b.validateObservable(c),!0});c.isValid=a.computed(function(){return c.__valid__()}),c.setError=function(a){c.error(a),c.__valid__(!1)},c.clearError=function(){c.error(null),c.__valid__(!0)};var f=c.subscribe(function(){c.isModified(!0)});c._disposeValidation=function(){c.isValid.dispose(),c.rules.removeAll(),c.isModified._subscriptions.change=[],c.isValidating._subscriptions.change=[],c.__valid__._subscriptions.change=[],f.dispose(),e.dispose(),delete c.rules,delete c.error,delete c.isValid,delete c.isValidating,delete c.__valid__,delete c.isModified}}else d===!1&&k.isValidatable(c)&&c._disposeValidation&&c._disposeValidation();return c},e.validateObservable=function(a){for(var e,f,g=0,h=a.rules(),i=h.length;i>g;g++)if(f=h[g],!f.condition||f.condition())if(e=b.rules[f.rule],e.async||f.async)d(a,e,f);else if(!c(a,e,f))return!1;return a.error(null),a.__valid__(!0),!0},a.validatedObservable=function(c){if(!b.utils.isObject(c))return a.observable(c).extend({validatable:!0});var d=a.observable(c);return d.errors=b.group(c),d.isValid=a.computed(function(){return 0===d.errors().length}),d},e.localize=function(a){var c;for(c in a)b.rules.hasOwnProperty(c)&&(b.rules[c].message=a[c])},a.applyBindingsWithValidation=function(c,d,e){var f,g,h=arguments.length;h>2?(f=d,g=e):2>h?f=document.body:arguments[1].nodeType?f=d:g=arguments[1],b.init(),g&&b.utils.setDomData(f,g),a.applyBindings(c,d)};var m=a.applyBindings;a.applyBindings=function(a,c){b.init(),m(a,c)}}); \ No newline at end of file +(function(n){typeof require=="function"&&typeof exports=="object"&&typeof module=="object"?n(require("knockout"),exports):typeof define=="function"&&define.amd?define(["knockout","exports"],n):n(ko,ko.validation={})})(function(n,t){function e(t,i,r){return i.validator(t(),r.params===undefined?!0:r.params)?!0:(t.error(n.validation.formatMessage(r.message||i.message,r.params)),t.__valid__(!1),!1)}function o(t,i,r){t.isValidating(!0);var u=function(u){var f=!1,e="";if(!t.__valid__()){t.isValidating(!1);return}u.message?(f=u.isValid,e=u.message):f=u;f||(t.error(n.validation.formatMessage(e||r.message||i.message,r.params)),t.__valid__(f));t.isValidating(!1)};i.validator(t(),r.params||!0,u)}var r,i,u,f;if(typeof n===undefined)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";n.validation=t;r={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",grouping:{deep:!1,observable:!0}};i=n.utils.extend({},r);i.html5Attributes=["required","pattern","min","max","step"];i.html5InputTypes=["email","number","date"];i.reset=function(){n.utils.extend(i,r)};n.validation.configuration=i;n.validation.utils=function(){var r=(new Date).getTime(),i={},t="__ko_validation__";return{isArray:function(n){return n.isArray||Object.prototype.toString.call(n)==="[object Array]"},isObject:function(n){return n!==null&&typeof n=="object"},values:function(n){var i=[],t;for(t in n)n.hasOwnProperty(t)&&i.push(n[t]);return i},getValue:function(n){return typeof n=="function"?n():n},hasAttribute:function(n,t){return n.getAttribute(t)!==null},getAttribute:function(n,t){return n.getAttribute(t)},setAttribute:function(n,t,i){return n.setAttribute(t,i)},isValidatable:function(n){return n&&n.rules&&n.isValid&&n.isModified},insertAfter:function(n,t){n.parentNode.insertBefore(t,n.nextSibling)},newId:function(){return r+=1},getConfigOptions:function(t){var i=n.validation.utils.contextFor(t);return i||n.validation.configuration},setDomData:function(r,u){var f=r[t];f||(r[t]=f=n.validation.utils.newId());i[f]=u},getDomData:function(n){var r=n[t];return r?i[r]:undefined},contextFor:function(t){switch(t.nodeType){case 1:case 8:var i=n.validation.utils.getDomData(t);if(i)return i;if(t.parentNode)return n.validation.utils.contextFor(t.parentNode)}return undefined},isEmptyVal:function(n){return n===undefined?!0:n===null?!0:n===""?!0:void 0},getOriginalElementTitle:function(t){var i=n.validation.utils.getAttribute(t,"data-orig-title"),r=t.title,u=n.validation.utils.hasAttribute(t,"data-orig-title");return u?i:r},async:function(n){window.setImmediate?window.setImmediate(n):window.setTimeout(n,0)}}}();u=function(){var r=0,i=n.validation.configuration,t=n.validation.utils;return{init:function(t,u){r>0&&!u||(t=t||{},t.errorElementClass=t.errorElementClass||t.errorClass||i.errorElementClass,t.errorMessageClass=t.errorMessageClass||t.errorClass||i.errorMessageClass,n.utils.extend(i,t),i.registerExtenders&&n.validation.registerExtenders(),r=1)},configure:function(t){n.validation.init(t)},reset:n.validation.configuration.reset,group:function(r,u){u=n.utils.extend(n.utils.extend({},i.grouping),u);var e=n.observableArray([]),f=null,o=function o(i,r){var s=[],f=n.utils.unwrapObservable(i);r=r!==undefined?r:u.deep?1:-1;n.isObservable(i)&&(i.isValid||i.extend({validatable:!0}),e.push(i));f&&(t.isArray(f)?s=f:t.isObject(f)&&(s=t.values(f)));r!==0&&n.utils.arrayForEach(s,function(n){n&&!n.nodeType&&o(n,r+1)})};return u.observable?(o(r),f=n.computed(function(){var t=[];return n.utils.arrayForEach(e(),function(n){n.isValid()||t.push(n.error)}),t})):f=function(){var t=[];return e([]),o(r),n.utils.arrayForEach(e(),function(n){n.isValid()||t.push(n.error)}),t},f.showAllMessages=function(t){t===undefined&&(t=!0);f();n.utils.arrayForEach(e(),function(n){n.isModified(t)})},r.errors=f,r.isValid=function(){return r.errors().length===0},r.isAnyMessageShown=function(){var t=!1;return f(),n.utils.arrayForEach(e(),function(n){!n.isValid()&&n.isModified()&&(t=!0)}),t},f},formatMessage:function(t,i){return typeof t=="function"?t(i):t.replace(/\{0\}/gi,n.utils.unwrapObservable(i))},addRule:function(n,t){return n.extend({validatable:!0}),n.rules.push(t),n},addAnonymousRule:function(i,r){var u=t.newId();r.message===undefined&&(r.message="Error");n.validation.rules[u]=r;n.validation.addRule(i,{rule:u,params:r.params})},addExtender:function(i){n.extenders[i]=function(r,u){return u.message||u.onlyIf?n.validation.addRule(r,{rule:i,message:u.message,params:t.isEmptyVal(u.params)?!0:u.params,condition:u.onlyIf}):n.validation.addRule(r,{rule:i,params:u})}},registerExtenders:function(){if(i.registerExtenders)for(var t in n.validation.rules)n.validation.rules.hasOwnProperty(t)&&(n.extenders[t]||n.validation.addExtender(t))},insertValidationMessage:function(n){var i=document.createElement("SPAN");return i.className=t.getConfigOptions(n).errorMessageClass,t.insertAfter(n,i),i},parseInputValidationAttributes:function(i,r){n.utils.arrayForEach(n.validation.configuration.html5Attributes,function(u){t.hasAttribute(i,u)&&n.validation.addRule(r(),{rule:u,params:i.getAttribute(u)||!0})});var u=i.getAttribute("type");n.utils.arrayForEach(n.validation.configuration.html5InputTypes,function(t){t===u&&n.validation.addRule(r(),{rule:t==="date"?"dateISO":t,params:!0})})},writeInputValidationAttributes:function(t,i){var r=i(),u;r&&r.rules&&(u=r.rules(),n.utils.arrayForEach(n.validation.configuration.html5Attributes,function(i){var f,r=n.utils.arrayFirst(u,function(n){return n.rule.toLowerCase()===i.toLowerCase()});r&&(f=r.params,r.rule==="pattern"&&r.params instanceof RegExp&&(f=r.params.source),t.setAttribute(i,f))}),u=null)},makeBindingHandlerValidatable:function(t){var i=n.bindingHandlers[t].init;n.bindingHandlers[t].init=function(t,r,u,f,e){return i(t,r,u,f,e),n.bindingHandlers.validationCore.init(t,r,u,f,e)}}}}();n.utils.extend(n.validation,u);n.validation.rules={};n.validation.rules.required={validator:function(n,t){var i;return n===undefined||n===null?!t:(i=n,typeof n=="string"&&(i=n.replace(/^\s+|\s+$/g,"")),!t)?!0:(i+"").length>0},message:"This field is required."};n.validation.rules.min={validator:function(t,i){return n.validation.utils.isEmptyVal(t)||t>=i},message:"Please enter a value greater than or equal to {0}."};n.validation.rules.max={validator:function(t,i){return n.validation.utils.isEmptyVal(t)||t<=i},message:"Please enter a value less than or equal to {0}."};n.validation.rules.minLength={validator:function(t,i){return n.validation.utils.isEmptyVal(t)||t.length>=i},message:"Please enter at least {0} characters."};n.validation.rules.maxLength={validator:function(t,i){return n.validation.utils.isEmptyVal(t)||t.length<=i},message:"Please enter no more than {0} characters."};n.validation.rules.pattern={validator:function(t,i){return n.validation.utils.isEmptyVal(t)||t.toString().match(i)!==null},message:"Please check this value."};n.validation.rules.step={validator:function(t,i){if(n.validation.utils.isEmptyVal(t)||i==="any")return!0;var r=t*100%(i*100);return Math.abs(r)<1e-5||Math.abs(1-r)<1e-5},message:"The value must increment by {0}"};n.validation.rules.email={validator:function(t,i){return i?n.validation.utils.isEmptyVal(t)||i&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(t):!0},message:"Please enter a proper email address"};n.validation.rules.date={validator:function(t,i){return i?n.validation.utils.isEmptyVal(t)||i&&!/Invalid|NaN/.test(new Date(t)):!0},message:"Please enter a proper date"};n.validation.rules.dateISO={validator:function(t,i){return i?n.validation.utils.isEmptyVal(t)||i&&/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(t):!0},message:"Please enter a proper date"};n.validation.rules.number={validator:function(t,i){return i?n.validation.utils.isEmptyVal(t)||i&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(t):!0},message:"Please enter a number"};n.validation.rules.digit={validator:function(t,i){return i?n.validation.utils.isEmptyVal(t)||i&&/^\d+$/.test(t):!0},message:"Please enter a digit"};n.validation.rules.phoneUS={validator:function(t,i){return i?typeof t!="string"?!1:n.validation.utils.isEmptyVal(t)?!0:(t=t.replace(/\s+/g,""),i&&t.length>9&&t.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number"};n.validation.rules.equal={validator:function(t,i){var r=i;return t===n.validation.utils.getValue(r)},message:"Values must equal"};n.validation.rules.notEqual={validator:function(t,i){var r=i;return t!==n.validation.utils.getValue(r)},message:"Please choose another value."};n.validation.rules.unique={validator:function(t,i){var r=n.validation.utils.getValue(i.collection),u=n.validation.utils.getValue(i.externalValue),f=0;return!t||!r?!0:(n.utils.arrayFilter(n.utils.unwrapObservable(r),function(n){t===(i.valueAccessor?i.valueAccessor(n):n)&&f++}),f<(u!==undefined&&t!==u?1:2))},message:"Please make sure the value is unique."},function(){n.validation.registerExtenders()}();n.bindingHandlers.validationCore=function(){return{init:function(t,i){var r=n.validation.utils.getConfigOptions(t),u;r.parseInputAttributes&&n.validation.utils.async(function(){n.validation.parseInputValidationAttributes(t,i)});r.insertMessages&&n.validation.utils.isValidatable(i())&&(u=n.validation.insertValidationMessage(t),r.messageTemplate?n.renderTemplate(r.messageTemplate,{field:i()},null,u,"replaceNode"):n.applyBindingsToNode(u,{validationMessage:i()}));r.writeInputAttributes&&n.validation.utils.isValidatable(i())&&n.validation.writeInputValidationAttributes(t,i);r.decorateElement&&n.validation.utils.isValidatable(i())&&n.applyBindingsToNode(t,{validationElement:i()})},update:function(){}}}();n.validation.makeBindingHandlerValidatable("value");n.validation.makeBindingHandlerValidatable("checked");n.bindingHandlers.validationMessage={update:function(t,i){var r=i(),e=n.validation.utils.getConfigOptions(t),h=n.utils.unwrapObservable(r),u=!1,f=!1,o,s;r.extend({validatable:!0});u=r.isModified();f=r.isValid();o=function(){return!e.messagesOnModified||u?f?null:r.error:null};s=function(){return!e.messagesOnModified||u?!f:!1};n.bindingHandlers.text.update(t,o);n.bindingHandlers.visible.update(t,s)}};n.bindingHandlers.validationElement={update:function(t,i){var r=i(),u=n.validation.utils.getConfigOptions(t),h=n.utils.unwrapObservable(r),f=!1,e=!1,o;if(r.extend({validatable:!0}),f=r.isModified(),e=r.isValid(),o=function(){var n={},t=!u.decorateElementOnModified||f?!e:!1;return u.decorateElement||(t=!1),n[u.errorElementClass]=t,n},n.bindingHandlers.css.update(t,o),u.errorsAsTitle){var c=n.validation.utils.getAttribute(t,"data-orig-title"),l=t.title,a=n.validation.utils.getAttribute(t,"data-orig-title")==="true",s=function(){if(!u.errorsAsTitleOnModified||f)return e?{title:n.validation.utils.getOriginalElementTitle(t),"data-orig-title":null}:{title:r.error,"data-orig-title":n.validation.utils.getOriginalElementTitle(t)}};n.bindingHandlers.attr.update(t,s)}}};n.bindingHandlers.validationOptions=function(){return{init:function(t,i){var u=n.utils.unwrapObservable(i()),r;u&&(r=n.utils.extend({},n.validation.configuration),n.utils.extend(r,u),n.validation.utils.setDomData(t,r))}}}();n.extenders.validation=function(t,i){return n.utils.arrayForEach(n.validation.utils.isArray(i)?i:[i],function(i){n.validation.addAnonymousRule(t,i)}),t};n.extenders.validatable=function(t,i){var r,u;return i&&!n.validation.utils.isValidatable(t)?(t.error=n.observable(null),t.rules=n.observableArray(),t.isValidating=n.observable(!1),t.__valid__=n.observable(!0),t.isModified=n.observable(!1),r=n.computed(function(){var i=t(),r=t.rules();return n.validation.validateObservable(t),!0}),t.isValid=n.computed(function(){return t.__valid__()}),t.setError=function(n){t.error(n);t.__valid__(!1)},t.clearError=function(){t.error(null);t.__valid__(!0)},u=t.subscribe(function(){t.isModified(!0)}),t._disposeValidation=function(){t.isValid.dispose();t.rules.removeAll();t.isModified._subscriptions.change=[];t.isValidating._subscriptions.change=[];t.__valid__._subscriptions.change=[];u.dispose();r.dispose();delete t.rules;delete t.error;delete t.isValid;delete t.isValidating;delete t.__valid__;delete t.isModified}):i===!1&&n.validation.utils.isValidatable(t)&&t._disposeValidation&&t._disposeValidation(),t};n.validation.validateObservable=function(t){for(var u=0,r,i,f=t.rules(),s=f.length;u2?(u=i,f=r):e<2?u=document.body:arguments[1].nodeType?u=i:f=arguments[1];n.validation.init();f&&n.validation.utils.setDomData(u,f);n.applyBindings(t,i)};f=n.applyBindings;n.applyBindings=function(t,i){n.validation.init();f(t,i)};n.validatedObservable=function(t){if(!n.validation.utils.isObject(t))return n.observable(t).extend({validatable:!0});var i=n.observable(t);return i.errors=n.validation.group(t),i.isValid=n.computed(function(){return i.errors().length===0}),i}}); +//# sourceMappingURL=knockout.validation.min.js.map \ No newline at end of file diff --git a/Dist/knockout.validation.min.js.map b/Dist/knockout.validation.min.js.map new file mode 100644 index 00000000..2cb81bcf --- /dev/null +++ b/Dist/knockout.validation.min.js.map @@ -0,0 +1,8 @@ +{ +"version":3, +"file":"knockout.validation.min.js", +"lineCount":1, +"mappings":"CASC,QAAS,CAACA,CAAD,CAAU,CAGZ,OAAOC,OAAQ,EAAI,UAAW,EAAG,OAAOC,OAAQ,EAAI,QAAS,EAAG,OAAOC,MAAO,EAAI,QAAtF,CAEIH,CAAO,CAACC,OAAO,CAAC,UAAD,CAAY,CAAEC,OAAtB,CAFX,CAGW,OAAOE,MAAO,EAAI,UAAW,EAAGA,MAAOC,IAA3C,CAEHD,MAAM,CAAC,CAAC,UAAU,CAAE,SAAb,CAAuB,CAAEJ,CAA1B,CAFH,CAKHA,CAAO,CAACM,EAAE,CAAEA,EAAEC,WAAY,CAAE,CAAA,CAArB,CAXK,EAanB,CAAC,QAAS,CAAED,CAAE,CAAEJ,CAAN,CAAgB,CAo6B3BM,SAASA,CAAY,CAACC,CAAU,CAAEC,CAAI,CAAEC,CAAnB,CAAwB,CAE5C,OAAKD,CAAIE,UAAU,CAACH,CAAU,CAAA,CAAE,CAAEE,CAAGE,OAAQ,GAAIC,SAAU,CAAE,CAAA,CAAK,CAAEH,CAAGE,OAApD,C,CAOX,CAAA,C,EAJPJ,CAAUM,MAAM,CAACT,CAAEC,WAAWS,cAAc,CAACL,CAAGM,QAAS,EAAGP,CAAIO,QAAQ,CAAEN,CAAGE,OAAjC,CAA5B,CAAsE,CACtFJ,CAAUS,UAAU,CAAC,CAAA,CAAD,CAAO,CACpB,CAAA,EAPoC,CAa7CC,SAASA,CAAa,CAACV,CAAU,CAAEC,CAAI,CAAEC,CAAnB,CAAwB,CAC7CF,CAAUW,aAAa,CAAC,CAAA,CAAD,CAAM,CAE7B,IAAIC,EA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,CAAEC,QAAS,CAAClG,CAAS,CAAE8F,CAAZ,CAAsB,CAEjD7O,CAAEC,WAAWoF,KAAK,CAAA,CAAE,CAEpB/D,CAAiB,CAACyH,CAAS,CAAE8F,CAAZ,CAJgC,CAKjD,CAED7O,CAAEkP,oBAAqB,CAAEC,QAAS,CAACC,CAAD,CAAe,CAChD,GAAI,CAACpP,CAAEC,WAAWsB,MAAMiB,SAAS,CAAC4M,CAAD,EAAkB,OAAOpP,CAAEG,WAAW,CAACiP,CAAD,CAAc5N,OAAO,CAAC,CAAE,WAAW,CAAE,CAAA,CAAf,CAAD,CAAyB,CAErH,IAAIsK,EAAO9L,CAAEG,WAAW,CAACiP,CAAD,CAAc,CAMtC,OALAtD,CAAIpF,OAAQ,CAAE1G,CAAEC,WAAW2F,MAAM,CAACwJ,CAAD,CAAc,CAC/CtD,CAAI7K,QAAS,CAAEjB,CAAEyG,SAAS,CAAC,QAAS,CAAA,CAAG,CACtC,OAAOqF,CAAIpF,OAAO,CAAA,CAAEK,OAAQ,GAAI,CADM,CAAb,CAExB,CAEK+E,CATyC,CAtiCtB,CAA1B,C", +"sources":["knockout.validation.js"], +"names":["factory","require","exports","module","define","amd","ko","validation","validateSync","observable","rule","ctx","validator","params","undefined","error","formatMessage","message","__valid__","validateAsync","isValidating","callBack","valObj","isValid","msg","defaults","configuration","api","origApplyBindings","utils","extend","html5Attributes","html5InputTypes","reset","configuration.reset","seedId","Date","getTime","domData","domDataKey","isArray","o","Object","prototype","toString","call","isObject","values","r","i","hasOwnProperty","push","getValue","hasAttribute","node","attr","getAttribute","element","setAttribute","value","isValidatable","rules","isModified","insertAfter","newNode","parentNode","insertBefore","nextSibling","newId","getConfigOptions","options","contextFor","setDomData","data","key","getDomData","nodeType","context","isEmptyVal","val","getOriginalElementTitle","savedOriginalTitle","currentTitle","title","hasSavedOriginalTitle","async","expr","window","setImmediate","setTimeout","isInitialized","init","force","errorElementClass","errorClass","errorMessageClass","registerExtenders","configure","group","obj","grouping","validatables","observableArray","result","traverse","level","objValues","unwrapObservable","deep","isObservable","arrayForEach","computed","errors","showAllMessages","result.showAllMessages","show","obj.isValid","length","isAnyMessageShown","obj.isAnyMessageShown","invalidAndModifiedPresent","replace","addRule","addAnonymousRule","ruleObj","ruleName","addExtender","extenders","onlyIf","insertValidationMessage","span","document","createElement","className","parseInputValidationAttributes","valueAccessor","currentType","type","writeInputValidationAttributes","contexts","arrayFirst","toLowerCase","RegExp","source","makeBindingHandlerValidatable","handlerName","bindingHandlers",".init","allBindingsAccessor","viewModel","bindingContext","validationCore","required","testVal","min","max","minLength","maxLength","pattern","regex","match","step","dif","Math","abs","email","validate","test","date","dateISO","number","digit","phoneUS","phoneNumber","equal","otherValue","notEqual","unique","c","collection","external","externalValue","counter","arrayFilter","item","config","validationMessageElement","parseInputAttributes","insertMessages","messageTemplate","renderTemplate","applyBindingsToNode","writeInputAttributes","decorateElement","update","validationMessage","obsv","errorMsgAccessor","visiblityAccessor","messagesOnModified","text","visible","validationElement","cssSettingsAccessor","css","shouldShow","decorateElementOnModified","errorsAsTitle","origTitle","elementTitle","titleIsErrorMsg","errorMsgTitleAccessor","errorsAsTitleOnModified","validationOptions","newConfig","ko.extenders.validation","validatable","ko.extenders.validatable","enable","h_obsValidationTrigger","h_change","obs","ruleContexts","validateObservable","setError","observable.setError","clearError","observable.clearError","subscribe","_disposeValidation","observable._disposeValidation","dispose","removeAll","_subscriptions","change","ko.validation.validateObservable","len","condition","localize","ko.validation.localize","msgTranslations","applyBindingsWithValidation","ko.applyBindingsWithValidation","rootNode","arguments","body","applyBindings","ko.applyBindings","validatedObservable","ko.validatedObservable","initialValue"] +} diff --git a/Src/api.js b/Src/api.js new file mode 100644 index 00000000..d82a6095 --- /dev/null +++ b/Src/api.js @@ -0,0 +1,337 @@ +var api = (function () { + + var isInitialized = 0, + configuration = ko.validation.configuration, + utils = ko.validation.utils; + + return { + //Call this on startup + //any config can be overridden with the passed in options + init: function (options, force) { + //done run this multiple times if we don't really want to + if (isInitialized > 0 && !force) { + return; + } + + //becuase we will be accessing options properties it has to be an object at least + options = options || {}; + //if specific error classes are not provided then apply generic errorClass + //it has to be done on option so that options.errorClass can override default + //errorElementClass and errorMessage class but not those provided in options + options.errorElementClass = options.errorElementClass || options.errorClass || configuration.errorElementClass; + options.errorMessageClass = options.errorMessageClass || options.errorClass || configuration.errorMessageClass; + + ko.utils.extend(configuration, options); + + if (configuration.registerExtenders) { + ko.validation.registerExtenders(); + } + + isInitialized = 1; + }, + // backwards compatability + configure: function (options) { ko.validation.init(options); }, + + // resets the config back to its original state + reset: ko.validation.configuration.reset, + + // recursivly walks a viewModel and creates an object that + // provides validation information for the entire viewModel + // obj -> the viewModel to walk + // options -> { + // deep: false, // if true, will walk past the first level of viewModel properties + // observable: false // if true, returns a computed observable indicating if the viewModel is valid + // } + group: function group(obj, options) { // array of observables or viewModel + options = ko.utils.extend(ko.utils.extend({}, configuration.grouping), options); + + var validatables = ko.observableArray([]), + result = null, + + //anonymous, immediate function to traverse objects hierarchically + //if !options.deep then it will stop on top level + traverse = function traverse(obj, level) { + var objValues = [], + val = ko.utils.unwrapObservable(obj); + + //default level value depends on deep option. + level = (level !== undefined ? level : options.deep ? 1 : -1); + + // if object is observable then add it to the list + if (ko.isObservable(obj)) { + + //make sure it is validatable object + if (!obj.isValid) { obj.extend({ validatable: true }); } + validatables.push(obj); + } + + //get list of values either from array or object but ignore non-objects + if (val) { + if (utils.isArray(val)) { + objValues = val; + } else if (utils.isObject(val)) { + objValues = utils.values(val); + } + } + + //process recurisvely if it is deep grouping + if (level !== 0) { + ko.utils.arrayForEach(objValues, function (observable) { + + //but not falsy things and not HTML Elements + if (observable && !observable.nodeType) { traverse(observable, level + 1); } + }); + } + }; + + //if using observables then traverse structure once and add observables + if (options.observable) { + + traverse(obj); + + result = ko.computed(function () { + var errors = []; + ko.utils.arrayForEach(validatables(), function (observable) { + if (!observable.isValid()) { + errors.push(observable.error); + } + }); + return errors; + }); + + } else { //if not using observables then every call to error() should traverse the structure + result = function () { + var errors = []; + validatables([]); //clear validatables + traverse(obj); // and traverse tree again + ko.utils.arrayForEach(validatables(), function (observable) { + if (!observable.isValid()) { + errors.push(observable.error); + } + }); + return errors; + }; + + + } + + result.showAllMessages = function (show) { // thanks @heliosPortal + if (show === undefined) {//default to true + show = true; + } + + // ensure we have latest changes + result(); + + ko.utils.arrayForEach(validatables(), function (observable) { + observable.isModified(show); + }); + }; + + obj.errors = result; + obj.isValid = function () { + return obj.errors().length === 0; + }; + obj.isAnyMessageShown = function () { + var invalidAndModifiedPresent = false; + + // ensure we have latest changes + result(); + + ko.utils.arrayForEach(validatables(), function (observable) { + if (!observable.isValid() && observable.isModified()) { + invalidAndModifiedPresent = true; + } + }); + return invalidAndModifiedPresent; + }; + + return result; + }, + + formatMessage: function (message, params) { + if (typeof (message) === 'function') { + return message(params); + } + return message.replace(/\{0\}/gi, ko.utils.unwrapObservable(params)); + }, + + // addRule: + // This takes in a ko.observable and a Rule Context - which is just a rule name and params to supply to the validator + // ie: ko.validation.addRule(myObservable, { + // rule: 'required', + // params: true + // }); + // + addRule: function (observable, rule) { + observable.extend({ validatable: true }); + + //push a Rule Context to the observables local array of Rule Contexts + observable.rules.push(rule); + return observable; + }, + + // addAnonymousRule: + // Anonymous Rules essentially have all the properties of a Rule, but are only specific for a certain property + // and developers typically are wanting to add them on the fly or not register a rule with the 'ko.validation.rules' object + // + // Example: + // var test = ko.observable('something').extend{( + // validation: { + // validator: function(val, someOtherVal){ + // return true; + // }, + // message: "Something must be really wrong!', + // params: true + // } + // )}; + addAnonymousRule: function (observable, ruleObj) { + var ruleName = utils.newId(); + + if (ruleObj['message'] === undefined) { + ruleObj['message'] = 'Error'; + } + + //Create an anonymous rule to reference + ko.validation.rules[ruleName] = ruleObj; + + //add the anonymous rule to the observable + ko.validation.addRule(observable, { + rule: ruleName, + params: ruleObj.params + }); + }, + + addExtender: function (ruleName) { + ko.extenders[ruleName] = function (observable, params) { + //params can come in a few flavors + // 1. Just the params to be passed to the validator + // 2. An object containing the Message to be used and the Params to pass to the validator + // 3. A condition when the validation rule to be applied + // + // Example: + // var test = ko.observable(3).extend({ + // max: { + // message: 'This special field has a Max of {0}', + // params: 2, + // onlyIf: function() { + // return specialField.IsVisible(); + // } + // } + // )}; + // + if (params.message || params.onlyIf) { //if it has a message or condition object, then its an object literal to use + return ko.validation.addRule(observable, { + rule: ruleName, + message: params.message, + params: utils.isEmptyVal(params.params) ? true : params.params, + condition: params.onlyIf + }); + } else { + return ko.validation.addRule(observable, { + rule: ruleName, + params: params + }); + } + }; + }, + + // loops through all ko.validation.rules and adds them as extenders to + // ko.extenders + registerExtenders: function () { // root extenders optional, use 'validation' extender if would cause conflicts + if (configuration.registerExtenders) { + for (var ruleName in ko.validation.rules) { + if (ko.validation.rules.hasOwnProperty(ruleName)) { + if (!ko.extenders[ruleName]) { + ko.validation.addExtender(ruleName); + } + } + } + } + }, + + //creates a span next to the @element with the specified error class + insertValidationMessage: function (element) { + var span = document.createElement('SPAN'); + span.className = utils.getConfigOptions(element).errorMessageClass; + utils.insertAfter(element, span); + return span; + }, + + // if html-5 validation attributes have been specified, this parses + // the attributes on @element + parseInputValidationAttributes: function (element, valueAccessor) { + ko.utils.arrayForEach(ko.validation.configuration.html5Attributes, function (attr) { + if (utils.hasAttribute(element, attr)) { + ko.validation.addRule(valueAccessor(), { + rule: attr, + params: element.getAttribute(attr) || true + }); + } + }); + + var currentType = element.getAttribute('type'); + ko.utils.arrayForEach(ko.validation.configuration.html5InputTypes, function (type) { + if (type === currentType) { + ko.validation.addRule(valueAccessor(), { + rule: (type === 'date') ? 'dateISO' : type, + params: true + }); + } + }); + }, + + // writes html5 validation attributes on the element passed in + writeInputValidationAttributes: function (element, valueAccessor) { + var observable = valueAccessor(); + + if (!observable || !observable.rules) { + return; + } + + var contexts = observable.rules(); // observable array + + // loop through the attributes and add the information needed + ko.utils.arrayForEach(ko.validation.configuration.html5Attributes, function (attr) { + var params; + var ctx = ko.utils.arrayFirst(contexts, function (ctx) { + return ctx.rule.toLowerCase() === attr.toLowerCase(); + }); + + if (!ctx) { + return; + } + + params = ctx.params; + + // we have to do some special things for the pattern validation + if (ctx.rule === "pattern") { + if (ctx.params instanceof RegExp) { + params = ctx.params.source; // we need the pure string representation of the RegExpr without the //gi stuff + } + } + + // we have a rule matching a validation attribute at this point + // so lets add it to the element along with the params + element.setAttribute(attr, params); + }); + + contexts = null; + }, + + //take an existing binding handler and make it cause automatic validations + makeBindingHandlerValidatable: function (handlerName) { + var init = ko.bindingHandlers[handlerName].init; + + ko.bindingHandlers[handlerName].init = function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + + init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext); + + return ko.bindingHandlers['validationCore'].init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext); + }; + } + }; +}()); + +// expose api publicly +ko.utils.extend(ko.validation, api); \ No newline at end of file diff --git a/Src/bindingHandlers.js b/Src/bindingHandlers.js new file mode 100644 index 00000000..6a69fe1a --- /dev/null +++ b/Src/bindingHandlers.js @@ -0,0 +1,157 @@ +// The core binding handler +// this allows us to setup any value binding that internally always +// performs the same functionality +ko.bindingHandlers['validationCore'] = (function () { + + return { + init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + var config = ko.validation.utils.getConfigOptions(element); + + // parse html5 input validation attributes, optional feature + if (config.parseInputAttributes) { + ko.validation.utils.async(function () { ko.validation.parseInputValidationAttributes(element, valueAccessor); }); + } + + // if requested insert message element and apply bindings + if (config.insertMessages && ko.validation.utils.isValidatable(valueAccessor())) { + + // insert the + var validationMessageElement = ko.validation.insertValidationMessage(element); + + // if we're told to use a template, make sure that gets rendered + if (config.messageTemplate) { + ko.renderTemplate(config.messageTemplate, { field: valueAccessor() }, null, validationMessageElement, 'replaceNode'); + } else { + ko.applyBindingsToNode(validationMessageElement, { validationMessage: valueAccessor() }); + } + } + + // write the html5 attributes if indicated by the config + if (config.writeInputAttributes && ko.validation.utils.isValidatable(valueAccessor())) { + + ko.validation.writeInputValidationAttributes(element, valueAccessor); + } + + // if requested, add binding to decorate element + if (config.decorateElement && ko.validation.utils.isValidatable(valueAccessor())) { + ko.applyBindingsToNode(element, { validationElement: valueAccessor() }); + } + }, + + update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + // hook for future extensibility + } + }; + +}()); + +// override for KO's default 'value' and 'checked' bindings +ko.validation.makeBindingHandlerValidatable("value"); +ko.validation.makeBindingHandlerValidatable("checked"); + + +ko.bindingHandlers['validationMessage'] = { // individual error message, if modified or post binding + update: function (element, valueAccessor) { + var obsv = valueAccessor(), + config = ko.validation.utils.getConfigOptions(element), + val = ko.utils.unwrapObservable(obsv), + msg = null, + isModified = false, + isValid = false; + + obsv.extend({ validatable: true }); + + isModified = obsv.isModified(); + isValid = obsv.isValid(); + + // create a handler to correctly return an error message + var errorMsgAccessor = function () { + if (!config.messagesOnModified || isModified) { + return isValid ? null : obsv.error; + } else { + return null; + } + }; + + //toggle visibility on validation messages when validation hasn't been evaluated, or when the object isValid + var visiblityAccessor = function () { + return (!config.messagesOnModified || isModified) ? !isValid : false; + }; + + ko.bindingHandlers.text.update(element, errorMsgAccessor); + ko.bindingHandlers.visible.update(element, visiblityAccessor); + } +}; + +ko.bindingHandlers['validationElement'] = { + update: function (element, valueAccessor) { + var obsv = valueAccessor(), + config = ko.validation.utils.getConfigOptions(element), + val = ko.utils.unwrapObservable(obsv), + msg = null, + isModified = false, + isValid = false; + + obsv.extend({ validatable: true }); + + isModified = obsv.isModified(); + isValid = obsv.isValid(); + + // create an evaluator function that will return something like: + // css: { validationElement: true } + var cssSettingsAccessor = function () { + var css = {}; + + var shouldShow = ((!config.decorateElementOnModified || isModified) ? !isValid : false); + + if (!config.decorateElement) { shouldShow = false; } + + // css: { validationElement: false } + css[config.errorElementClass] = shouldShow; + + return css; + }; + + //add or remove class on the element; + ko.bindingHandlers.css.update(element, cssSettingsAccessor); + if (!config.errorsAsTitle) { return; } + + var origTitle = ko.validation.utils.getAttribute(element, 'data-orig-title'), + elementTitle = element.title, + titleIsErrorMsg = ko.validation.utils.getAttribute(element, 'data-orig-title') === "true"; + + var errorMsgTitleAccessor = function () { + if (!config.errorsAsTitleOnModified || isModified) { + if (!isValid) { + return { title: obsv.error, 'data-orig-title': ko.validation.utils.getOriginalElementTitle(element) }; + } else { + return { title: ko.validation.utils.getOriginalElementTitle(element), 'data-orig-title': null }; + } + } + }; + ko.bindingHandlers.attr.update(element, errorMsgTitleAccessor); + } +}; + +// ValidationOptions: +// This binding handler allows you to override the initial config by setting any of the options for a specific element or context of elements +// +// Example: +//
+// +// +//
+ko.bindingHandlers['validationOptions'] = (function () { + return { + init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + var options = ko.utils.unwrapObservable(valueAccessor()); + if (options) { + var newConfig = ko.utils.extend({}, ko.validation.configuration); + ko.utils.extend(newConfig, options); + + //store the validation options on the node so we can retrieve it later + ko.validation.utils.setDomData(element, newConfig); + } + } + }; +}()); diff --git a/Src/configuration.js b/Src/configuration.js new file mode 100644 index 00000000..6572d7e0 --- /dev/null +++ b/Src/configuration.js @@ -0,0 +1,33 @@ +/*global ko: false*/ + +var defaults = { + registerExtenders: true, + messagesOnModified: true, + errorsAsTitle: true, // enables/disables showing of errors as title attribute of the target element. + errorsAsTitleOnModified: false, // shows the error when hovering the input field (decorateElement must be true) + messageTemplate: null, + insertMessages: true, // automatically inserts validation messages as + parseInputAttributes: false, // parses the HTML5 validation attribute from a form element and adds that to the object + writeInputAttributes: false, // adds HTML5 input validation attributes to form elements that ko observable's are bound to + decorateElement: false, // false to keep backward compatibility + decorateElementOnModified: true,// true to keep backward compatibility + errorClass: null, // single class for error message and element + errorElementClass: 'validationElement', // class to decorate error element + errorMessageClass: 'validationMessage', // class to decorate error message + grouping: { + deep: false, //by default grouping is shallow + observable: true //and using observables + } +}; + +// make a copy so we can use 'reset' later +var configuration = ko.utils.extend({}, defaults); + +configuration.html5Attributes = ['required', 'pattern', 'min', 'max', 'step']; +configuration.html5InputTypes = ['email', 'number', 'date']; + +configuration.reset = function () { + ko.utils.extend(configuration, defaults); +}; + +ko.validation.configuration = configuration; \ No newline at end of file diff --git a/Src/extenders.js b/Src/extenders.js new file mode 100644 index 00000000..15e4589a --- /dev/null +++ b/Src/extenders.js @@ -0,0 +1,193 @@ +// Validation Extender: +// This is for creating custom validation logic on the fly +// Example: +// var test = ko.observable('something').extend{( +// validation: { +// validator: function(val, someOtherVal){ +// return true; +// }, +// message: "Something must be really wrong!', +// params: true +// } +// )}; +ko.extenders['validation'] = function (observable, rules) { // allow single rule or array + ko.utils.arrayForEach(ko.validation.utils.isArray(rules) ? rules : [rules], function (rule) { + // the 'rule' being passed in here has no name to identify a core Rule, + // so we add it as an anonymous rule + // If the developer is wanting to use a core Rule, but use a different message see the 'addExtender' logic for examples + ko.validation.addAnonymousRule(observable, rule); + }); + return observable; +}; + +//This is the extender that makes a Knockout Observable also 'Validatable' +//examples include: +// 1. var test = ko.observable('something').extend({validatable: true}); +// this will ensure that the Observable object is setup properly to respond to rules +// +// 2. test.extend({validatable: false}); +// this will remove the validation properties from the Observable object should you need to do that. +ko.extenders['validatable'] = function (observable, enable) { + if (enable && !ko.validation.utils.isValidatable(observable)) { + + observable.error = ko.observable(null); // holds the error message, we only need one since we stop processing validators when one is invalid + + // observable.rules: + // ObservableArray of Rule Contexts, where a Rule Context is simply the name of a rule and the params to supply to it + // + // Rule Context = { rule: '', params: '', message: '' } + observable.rules = ko.observableArray(); //holds the rule Contexts to use as part of validation + + //in case async validation is occuring + observable.isValidating = ko.observable(false); + + //the true holder of whether the observable is valid or not + observable.__valid__ = ko.observable(true); + + observable.isModified = ko.observable(false); + + // we use a computed here to ensure that anytime a dependency changes, the + // validation logic evaluates + var h_obsValidationTrigger = ko.computed(function () { + var obs = observable(), + ruleContexts = observable.rules(); + + ko.validation.validateObservable(observable); + + return true; + }); + + // a semi-protected observable + observable.isValid = ko.computed(function () { + return observable.__valid__(); + }); + + //manually set error state + observable.setError = function (error) { + observable.error(error); + observable.__valid__(false); + }; + + //manually clear error state + observable.clearError = function () { + observable.error(null); + observable.__valid__(true); + }; + + //subscribe to changes in the observable + var h_change = observable.subscribe(function () { + observable.isModified(true); + }); + + observable._disposeValidation = function () { + //first dispose of the subscriptions + observable.isValid.dispose(); + observable.rules.removeAll(); + observable.isModified._subscriptions['change'] = []; + observable.isValidating._subscriptions['change'] = []; + observable.__valid__._subscriptions['change'] = []; + h_change.dispose(); + h_obsValidationTrigger.dispose(); + + delete observable['rules']; + delete observable['error']; + delete observable['isValid']; + delete observable['isValidating']; + delete observable['__valid__']; + delete observable['isModified']; + }; + } else if (enable === false && ko.validation.utils.isValidatable(observable)) { + + if (observable._disposeValidation) { + observable._disposeValidation(); + } + } + return observable; +}; + +function validateSync(observable, rule, ctx) { + //Execute the validator and see if its valid + if (!rule.validator(observable(), ctx.params === undefined ? true : ctx.params)) { // default param is true, eg. required = true + + //not valid, so format the error message and stick it in the 'error' variable + observable.error(ko.validation.formatMessage(ctx.message || rule.message, ctx.params)); + observable.__valid__(false); + return false; + } else { + return true; + } +} + +function validateAsync(observable, rule, ctx) { + observable.isValidating(true); + + var callBack = function (valObj) { + var isValid = false, + msg = ''; + + if (!observable.__valid__()) { + + // since we're returning early, make sure we turn this off + observable.isValidating(false); + + return; //if its already NOT valid, don't add to that + } + + //we were handed back a complex object + if (valObj['message']) { + isValid = valObj.isValid; + msg = valObj.message; + } else { + isValid = valObj; + } + + if (!isValid) { + //not valid, so format the error message and stick it in the 'error' variable + observable.error(ko.validation.formatMessage(msg || ctx.message || rule.message, ctx.params)); + observable.__valid__(isValid); + } + + // tell it that we're done + observable.isValidating(false); + }; + + //fire the validator and hand it the callback + rule.validator(observable(), ctx.params || true, callBack); +} + +ko.validation.validateObservable = function (observable) { + var i = 0, + rule, // the rule validator to execute + ctx, // the current Rule Context for the loop + ruleContexts = observable.rules(), //cache for iterator + len = ruleContexts.length; //cache for iterator + + for (; i < len; i++) { + + //get the Rule Context info to give to the core Rule + ctx = ruleContexts[i]; + + // checks an 'onlyIf' condition + if (ctx.condition && !ctx.condition()) { + continue; + } + + //get the core Rule to use for validation + rule = ko.validation.rules[ctx.rule]; + + if (rule['async'] || ctx['async']) { + //run async validation + validateAsync(observable, rule, ctx); + + } else { + //run normal sync validation + if (!validateSync(observable, rule, ctx)) { + return false; //break out of the loop + } + } + } + //finally if we got this far, make the observable valid again! + observable.error(null); + observable.__valid__(true); + return true; +}; \ No newline at end of file diff --git a/Src/knockout.validation.js b/Src/knockout.validation.js deleted file mode 100644 index cd834d32..00000000 --- a/Src/knockout.validation.js +++ /dev/null @@ -1,1128 +0,0 @@ -/*globals - require: false, - exports: false, - define: false, - ko: false -*/ - -(function (factory) { - // Module systems magic dance. - - if (typeof require === "function" && typeof exports === "object" && typeof module === "object") { - // CommonJS or Node: hard-coded dependency on "knockout" - factory(require("knockout"), exports); - } else if (typeof define === "function" && define["amd"]) { - // AMD anonymous module with hard-coded dependency on "knockout" - define(["knockout", "exports"], factory); - } else { - // - + diff --git a/gruntfile.js b/gruntfile.js index bd180283..e6092265 100644 --- a/gruntfile.js +++ b/gruntfile.js @@ -20,7 +20,16 @@ module.exports = function (grunt) { dist: { src: [ "<%= meta.banner %>", - "src/<%= pkg.name %>.js", + "src/ko.validation.start.frag", + "src/configuration.js", + "src/utils.js", + "src/api.js", + "src/rules.js", + "src/bindingHandlers.js", + "src/extenders.js", + "src/localization.js", + "src/ko.extensions.js", + "src/ko.validation.end.frag", ], dest: "dist/<%= pkg.name %>.js" } @@ -58,6 +67,6 @@ module.exports = function (grunt) { grunt.loadNpmTasks("grunt-clear"); // Default task. - grunt.registerTask("default", ["qunit", "jshint", "concat", "uglify"]); - grunt.registerTask("test", ["qunit", "jshint"]); + grunt.registerTask("default", ["test", "uglify"]); + grunt.registerTask("test", ["concat", "qunit", "jshint"]); }; From 2fde9b6976cc4009dba8bb3563d570b01e9cdf9c Mon Sep 17 00:00:00 2001 From: Steve Greatrex Date: Sat, 5 Oct 2013 15:57:22 +0100 Subject: [PATCH 035/165] Added build status notification --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 0fd23f40..ae39d0df 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ #Knockout Validation A KnockoutJS Plugin for model and property validation +[![Build Status](https://travis-ci.org/Knockout-Contrib/Knockout-Validation.png)](https://travis-ci.org/Knockout-Contrib/Knockout-Validation) + Contributors: * [Eric Barnard](https://github.com/ericmbarnard) From f3d99fdc7c43769cdcc9dae3d31897b885c4444f Mon Sep 17 00:00:00 2001 From: Steve Greatrex Date: Fri, 18 Oct 2013 21:14:16 +0100 Subject: [PATCH 036/165] Added setRules implementation --- Dist/knockout.validation.js | 45 ++++++++++++++++++ Dist/knockout.validation.min.js | 10 +++- Src/api.js | 45 ++++++++++++++++++ Tests/validation-tests.js | 84 +++++++++++++++++++++++++++++++++ 4 files changed, 182 insertions(+), 2 deletions(-) diff --git a/Dist/knockout.validation.js b/Dist/knockout.validation.js index cd20bb9e..9f4fa3d1 100644 --- a/Dist/knockout.validation.js +++ b/Dist/knockout.validation.js @@ -489,6 +489,51 @@ ko.validation.configuration = configuration;;ko.validation.utils = (function () return ko.bindingHandlers['validationCore'].init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext); }; + }, + + // visit an objects properties and apply validation rules from a definition + setRules: function (target, definition) { + var setRules = function (target, definition) { + if (!target || !definition) { return; } + + for (var prop in definition) { + if (!definition.hasOwnProperty(prop)) { continue; } + var ruleDefinitions = definition[prop]; + + //check the target property exists and has a value + if (!target[prop]) { continue; } + var targetValue = target[prop], + unwrappedTargetValue = ko.utils.unwrapObservable(targetValue), + rules = {}, + nonRules = {}; + + for (var rule in ruleDefinitions) { + if (!ruleDefinitions.hasOwnProperty(rule)) { continue; } + if (ko.validation.rules[rule]) { + rules[rule] = ruleDefinitions[rule]; + } else { + nonRules[rule] = ruleDefinitions[rule]; + } + } + + //apply rules + if (ko.isObservable(targetValue)) { + targetValue.extend(rules); + } + + //then apply child rules + //if it's an array, apply rules to all children + if (unwrappedTargetValue && utils.isArray(unwrappedTargetValue)) { + for (var i = 0; i < unwrappedTargetValue.length; i++) { + setRules(unwrappedTargetValue[i], nonRules); + } + //otherwise, just apply to this property + } else { + setRules(unwrappedTargetValue, nonRules); + } + } + }; + setRules(target, definition); } }; }()); diff --git a/Dist/knockout.validation.min.js b/Dist/knockout.validation.min.js index da44a3b9..2a457c84 100644 --- a/Dist/knockout.validation.min.js +++ b/Dist/knockout.validation.min.js @@ -1,2 +1,8 @@ -(function(n){typeof require=="function"&&typeof exports=="object"&&typeof module=="object"?n(require("knockout"),exports):typeof define=="function"&&define.amd?define(["knockout","exports"],n):n(ko,ko.validation={})})(function(n,t){function e(t,i,r){return i.validator(t(),r.params===undefined?!0:r.params)?!0:(t.error(n.validation.formatMessage(r.message||i.message,r.params)),t.__valid__(!1),!1)}function o(t,i,r){t.isValidating(!0);var u=function(u){var f=!1,e="";if(!t.__valid__()){t.isValidating(!1);return}u.message?(f=u.isValid,e=u.message):f=u;f||(t.error(n.validation.formatMessage(e||r.message||i.message,r.params)),t.__valid__(f));t.isValidating(!1)};i.validator(t(),r.params||!0,u)}var r,i,u,f;if(typeof n===undefined)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";n.validation=t;r={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",grouping:{deep:!1,observable:!0}};i=n.utils.extend({},r);i.html5Attributes=["required","pattern","min","max","step"];i.html5InputTypes=["email","number","date"];i.reset=function(){n.utils.extend(i,r)};n.validation.configuration=i;n.validation.utils=function(){var r=(new Date).getTime(),i={},t="__ko_validation__";return{isArray:function(n){return n.isArray||Object.prototype.toString.call(n)==="[object Array]"},isObject:function(n){return n!==null&&typeof n=="object"},values:function(n){var i=[],t;for(t in n)n.hasOwnProperty(t)&&i.push(n[t]);return i},getValue:function(n){return typeof n=="function"?n():n},hasAttribute:function(n,t){return n.getAttribute(t)!==null},getAttribute:function(n,t){return n.getAttribute(t)},setAttribute:function(n,t,i){return n.setAttribute(t,i)},isValidatable:function(n){return n&&n.rules&&n.isValid&&n.isModified},insertAfter:function(n,t){n.parentNode.insertBefore(t,n.nextSibling)},newId:function(){return r+=1},getConfigOptions:function(t){var i=n.validation.utils.contextFor(t);return i||n.validation.configuration},setDomData:function(r,u){var f=r[t];f||(r[t]=f=n.validation.utils.newId());i[f]=u},getDomData:function(n){var r=n[t];return r?i[r]:undefined},contextFor:function(t){switch(t.nodeType){case 1:case 8:var i=n.validation.utils.getDomData(t);if(i)return i;if(t.parentNode)return n.validation.utils.contextFor(t.parentNode)}return undefined},isEmptyVal:function(n){return n===undefined?!0:n===null?!0:n===""?!0:void 0},getOriginalElementTitle:function(t){var i=n.validation.utils.getAttribute(t,"data-orig-title"),r=t.title,u=n.validation.utils.hasAttribute(t,"data-orig-title");return u?i:r},async:function(n){window.setImmediate?window.setImmediate(n):window.setTimeout(n,0)}}}();u=function(){var r=0,i=n.validation.configuration,t=n.validation.utils;return{init:function(t,u){r>0&&!u||(t=t||{},t.errorElementClass=t.errorElementClass||t.errorClass||i.errorElementClass,t.errorMessageClass=t.errorMessageClass||t.errorClass||i.errorMessageClass,n.utils.extend(i,t),i.registerExtenders&&n.validation.registerExtenders(),r=1)},configure:function(t){n.validation.init(t)},reset:n.validation.configuration.reset,group:function(r,u){u=n.utils.extend(n.utils.extend({},i.grouping),u);var e=n.observableArray([]),f=null,o=function o(i,r){var s=[],f=n.utils.unwrapObservable(i);r=r!==undefined?r:u.deep?1:-1;n.isObservable(i)&&(i.isValid||i.extend({validatable:!0}),e.push(i));f&&(t.isArray(f)?s=f:t.isObject(f)&&(s=t.values(f)));r!==0&&n.utils.arrayForEach(s,function(n){n&&!n.nodeType&&o(n,r+1)})};return u.observable?(o(r),f=n.computed(function(){var t=[];return n.utils.arrayForEach(e(),function(n){n.isValid()||t.push(n.error)}),t})):f=function(){var t=[];return e([]),o(r),n.utils.arrayForEach(e(),function(n){n.isValid()||t.push(n.error)}),t},f.showAllMessages=function(t){t===undefined&&(t=!0);f();n.utils.arrayForEach(e(),function(n){n.isModified(t)})},r.errors=f,r.isValid=function(){return r.errors().length===0},r.isAnyMessageShown=function(){var t=!1;return f(),n.utils.arrayForEach(e(),function(n){!n.isValid()&&n.isModified()&&(t=!0)}),t},f},formatMessage:function(t,i){return typeof t=="function"?t(i):t.replace(/\{0\}/gi,n.utils.unwrapObservable(i))},addRule:function(n,t){return n.extend({validatable:!0}),n.rules.push(t),n},addAnonymousRule:function(i,r){var u=t.newId();r.message===undefined&&(r.message="Error");n.validation.rules[u]=r;n.validation.addRule(i,{rule:u,params:r.params})},addExtender:function(i){n.extenders[i]=function(r,u){return u.message||u.onlyIf?n.validation.addRule(r,{rule:i,message:u.message,params:t.isEmptyVal(u.params)?!0:u.params,condition:u.onlyIf}):n.validation.addRule(r,{rule:i,params:u})}},registerExtenders:function(){if(i.registerExtenders)for(var t in n.validation.rules)n.validation.rules.hasOwnProperty(t)&&(n.extenders[t]||n.validation.addExtender(t))},insertValidationMessage:function(n){var i=document.createElement("SPAN");return i.className=t.getConfigOptions(n).errorMessageClass,t.insertAfter(n,i),i},parseInputValidationAttributes:function(i,r){n.utils.arrayForEach(n.validation.configuration.html5Attributes,function(u){t.hasAttribute(i,u)&&n.validation.addRule(r(),{rule:u,params:i.getAttribute(u)||!0})});var u=i.getAttribute("type");n.utils.arrayForEach(n.validation.configuration.html5InputTypes,function(t){t===u&&n.validation.addRule(r(),{rule:t==="date"?"dateISO":t,params:!0})})},writeInputValidationAttributes:function(t,i){var r=i(),u;r&&r.rules&&(u=r.rules(),n.utils.arrayForEach(n.validation.configuration.html5Attributes,function(i){var f,r=n.utils.arrayFirst(u,function(n){return n.rule.toLowerCase()===i.toLowerCase()});r&&(f=r.params,r.rule==="pattern"&&r.params instanceof RegExp&&(f=r.params.source),t.setAttribute(i,f))}),u=null)},makeBindingHandlerValidatable:function(t){var i=n.bindingHandlers[t].init;n.bindingHandlers[t].init=function(t,r,u,f,e){return i(t,r,u,f,e),n.bindingHandlers.validationCore.init(t,r,u,f,e)}}}}();n.utils.extend(n.validation,u);n.validation.rules={};n.validation.rules.required={validator:function(n,t){var i;return n===undefined||n===null?!t:(i=n,typeof n=="string"&&(i=n.replace(/^\s+|\s+$/g,"")),!t)?!0:(i+"").length>0},message:"This field is required."};n.validation.rules.min={validator:function(t,i){return n.validation.utils.isEmptyVal(t)||t>=i},message:"Please enter a value greater than or equal to {0}."};n.validation.rules.max={validator:function(t,i){return n.validation.utils.isEmptyVal(t)||t<=i},message:"Please enter a value less than or equal to {0}."};n.validation.rules.minLength={validator:function(t,i){return n.validation.utils.isEmptyVal(t)||t.length>=i},message:"Please enter at least {0} characters."};n.validation.rules.maxLength={validator:function(t,i){return n.validation.utils.isEmptyVal(t)||t.length<=i},message:"Please enter no more than {0} characters."};n.validation.rules.pattern={validator:function(t,i){return n.validation.utils.isEmptyVal(t)||t.toString().match(i)!==null},message:"Please check this value."};n.validation.rules.step={validator:function(t,i){if(n.validation.utils.isEmptyVal(t)||i==="any")return!0;var r=t*100%(i*100);return Math.abs(r)<1e-5||Math.abs(1-r)<1e-5},message:"The value must increment by {0}"};n.validation.rules.email={validator:function(t,i){return i?n.validation.utils.isEmptyVal(t)||i&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(t):!0},message:"Please enter a proper email address"};n.validation.rules.date={validator:function(t,i){return i?n.validation.utils.isEmptyVal(t)||i&&!/Invalid|NaN/.test(new Date(t)):!0},message:"Please enter a proper date"};n.validation.rules.dateISO={validator:function(t,i){return i?n.validation.utils.isEmptyVal(t)||i&&/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(t):!0},message:"Please enter a proper date"};n.validation.rules.number={validator:function(t,i){return i?n.validation.utils.isEmptyVal(t)||i&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(t):!0},message:"Please enter a number"};n.validation.rules.digit={validator:function(t,i){return i?n.validation.utils.isEmptyVal(t)||i&&/^\d+$/.test(t):!0},message:"Please enter a digit"};n.validation.rules.phoneUS={validator:function(t,i){return i?typeof t!="string"?!1:n.validation.utils.isEmptyVal(t)?!0:(t=t.replace(/\s+/g,""),i&&t.length>9&&t.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number"};n.validation.rules.equal={validator:function(t,i){var r=i;return t===n.validation.utils.getValue(r)},message:"Values must equal"};n.validation.rules.notEqual={validator:function(t,i){var r=i;return t!==n.validation.utils.getValue(r)},message:"Please choose another value."};n.validation.rules.unique={validator:function(t,i){var r=n.validation.utils.getValue(i.collection),u=n.validation.utils.getValue(i.externalValue),f=0;return!t||!r?!0:(n.utils.arrayFilter(n.utils.unwrapObservable(r),function(n){t===(i.valueAccessor?i.valueAccessor(n):n)&&f++}),f<(u!==undefined&&t!==u?1:2))},message:"Please make sure the value is unique."},function(){n.validation.registerExtenders()}();n.bindingHandlers.validationCore=function(){return{init:function(t,i){var r=n.validation.utils.getConfigOptions(t),u;r.parseInputAttributes&&n.validation.utils.async(function(){n.validation.parseInputValidationAttributes(t,i)});r.insertMessages&&n.validation.utils.isValidatable(i())&&(u=n.validation.insertValidationMessage(t),r.messageTemplate?n.renderTemplate(r.messageTemplate,{field:i()},null,u,"replaceNode"):n.applyBindingsToNode(u,{validationMessage:i()}));r.writeInputAttributes&&n.validation.utils.isValidatable(i())&&n.validation.writeInputValidationAttributes(t,i);r.decorateElement&&n.validation.utils.isValidatable(i())&&n.applyBindingsToNode(t,{validationElement:i()})},update:function(){}}}();n.validation.makeBindingHandlerValidatable("value");n.validation.makeBindingHandlerValidatable("checked");n.bindingHandlers.validationMessage={update:function(t,i){var r=i(),e=n.validation.utils.getConfigOptions(t),h=n.utils.unwrapObservable(r),u=!1,f=!1,o,s;r.extend({validatable:!0});u=r.isModified();f=r.isValid();o=function(){return!e.messagesOnModified||u?f?null:r.error:null};s=function(){return!e.messagesOnModified||u?!f:!1};n.bindingHandlers.text.update(t,o);n.bindingHandlers.visible.update(t,s)}};n.bindingHandlers.validationElement={update:function(t,i){var r=i(),u=n.validation.utils.getConfigOptions(t),h=n.utils.unwrapObservable(r),f=!1,e=!1,o;if(r.extend({validatable:!0}),f=r.isModified(),e=r.isValid(),o=function(){var n={},t=!u.decorateElementOnModified||f?!e:!1;return u.decorateElement||(t=!1),n[u.errorElementClass]=t,n},n.bindingHandlers.css.update(t,o),u.errorsAsTitle){var c=n.validation.utils.getAttribute(t,"data-orig-title"),l=t.title,a=n.validation.utils.getAttribute(t,"data-orig-title")==="true",s=function(){if(!u.errorsAsTitleOnModified||f)return e?{title:n.validation.utils.getOriginalElementTitle(t),"data-orig-title":null}:{title:r.error,"data-orig-title":n.validation.utils.getOriginalElementTitle(t)}};n.bindingHandlers.attr.update(t,s)}}};n.bindingHandlers.validationOptions=function(){return{init:function(t,i){var u=n.utils.unwrapObservable(i()),r;u&&(r=n.utils.extend({},n.validation.configuration),n.utils.extend(r,u),n.validation.utils.setDomData(t,r))}}}();n.extenders.validation=function(t,i){return n.utils.arrayForEach(n.validation.utils.isArray(i)?i:[i],function(i){n.validation.addAnonymousRule(t,i)}),t};n.extenders.validatable=function(t,i){var r,u;return i&&!n.validation.utils.isValidatable(t)?(t.error=n.observable(null),t.rules=n.observableArray(),t.isValidating=n.observable(!1),t.__valid__=n.observable(!0),t.isModified=n.observable(!1),r=n.computed(function(){var i=t(),r=t.rules();return n.validation.validateObservable(t),!0}),t.isValid=n.computed(function(){return t.__valid__()}),t.setError=function(n){t.error(n);t.__valid__(!1)},t.clearError=function(){t.error(null);t.__valid__(!0)},u=t.subscribe(function(){t.isModified(!0)}),t._disposeValidation=function(){t.isValid.dispose();t.rules.removeAll();t.isModified._subscriptions.change=[];t.isValidating._subscriptions.change=[];t.__valid__._subscriptions.change=[];u.dispose();r.dispose();delete t.rules;delete t.error;delete t.isValid;delete t.isValidating;delete t.__valid__;delete t.isModified}):i===!1&&n.validation.utils.isValidatable(t)&&t._disposeValidation&&t._disposeValidation(),t};n.validation.validateObservable=function(t){for(var u=0,r,i,f=t.rules(),s=f.length;u2?(u=i,f=r):e<2?u=document.body:arguments[1].nodeType?u=i:f=arguments[1];n.validation.init();f&&n.validation.utils.setDomData(u,f);n.applyBindings(t,i)};f=n.applyBindings;n.applyBindings=function(t,i){n.validation.init();f(t,i)};n.validatedObservable=function(t){if(!n.validation.utils.isObject(t))return n.observable(t).extend({validatable:!0});var i=n.observable(t);return i.errors=n.validation.group(t),i.isValid=n.computed(function(){return i.errors().length===0}),i}}); -//# sourceMappingURL=knockout.validation.min.js.map \ No newline at end of file +/*============================================================================= + Author: Eric M. Barnard - @ericmbarnard + License: MIT (http://opensource.org/licenses/mit-license.php) + + Description: Validation Library for KnockoutJS +=============================================================================== +*/ +!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(b,c,d){return c.validator(b(),void 0===d.params?!0:d.params)?!0:(b.error(a.validation.formatMessage(d.message||c.message,d.params)),b.__valid__(!1),!1)}function d(b,c,d){b.isValidating(!0);var e=function(e){var f=!1,g="";return b.__valid__()?(e.message?(f=e.isValid,g=e.message):f=e,f||(b.error(a.validation.formatMessage(g||d.message||c.message,d.params)),b.__valid__(f)),b.isValidating(!1),void 0):(b.isValidating(!1),void 0)};c.validator(b(),d.params||!0,e)}if(void 0===typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var e={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",grouping:{deep:!1,observable:!0}},f=a.utils.extend({},e);f.html5Attributes=["required","pattern","min","max","step"],f.html5InputTypes=["email","number","date"],f.reset=function(){a.utils.extend(f,e)},a.validation.configuration=f,a.validation.utils=function(){var b=(new Date).getTime(),c={},d="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return a&&a.rules&&a.isValid&&a.isModified},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return b+=1},getConfigOptions:function(b){var c=a.validation.utils.contextFor(b);return c||a.validation.configuration},setDomData:function(b,e){var f=b[d];f||(b[d]=f=a.validation.utils.newId()),c[f]=e},getDomData:function(a){var b=a[d];return b?c[b]:void 0},contextFor:function(b){switch(b.nodeType){case 1:case 8:var c=a.validation.utils.getDomData(b);if(c)return c;if(b.parentNode)return a.validation.utils.contextFor(b.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(b){var c=a.validation.utils.getAttribute(b,"data-orig-title"),d=b.title,e=a.validation.utils.hasAttribute(b,"data-orig-title");return e?c:d},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)}}}();var g=function(){var b=0,c=a.validation.configuration,d=a.validation.utils;return{init:function(d,e){b>0&&!e||(d=d||{},d.errorElementClass=d.errorElementClass||d.errorClass||c.errorElementClass,d.errorMessageClass=d.errorMessageClass||d.errorClass||c.errorMessageClass,a.utils.extend(c,d),c.registerExtenders&&a.validation.registerExtenders(),b=1)},configure:function(b){a.validation.init(b)},reset:a.validation.configuration.reset,group:function(b,e){e=a.utils.extend(a.utils.extend({},c.grouping),e);var f=a.observableArray([]),g=null,h=function i(b,c){var g=[],h=a.utils.unwrapObservable(b);c=void 0!==c?c:e.deep?1:-1,a.isObservable(b)&&(b.isValid||b.extend({validatable:!0}),f.push(b)),h&&(d.isArray(h)?g=h:d.isObject(h)&&(g=d.values(h))),0!==c&&a.utils.arrayForEach(g,function(a){a&&!a.nodeType&&i(a,c+1)})};return e.observable?(h(b),g=a.computed(function(){var b=[];return a.utils.arrayForEach(f(),function(a){a.isValid()||b.push(a.error)}),b})):g=function(){var c=[];return f([]),h(b),a.utils.arrayForEach(f(),function(a){a.isValid()||c.push(a.error)}),c},g.showAllMessages=function(b){void 0===b&&(b=!0),g(),a.utils.arrayForEach(f(),function(a){a.isModified(b)})},b.errors=g,b.isValid=function(){return 0===b.errors().length},b.isAnyMessageShown=function(){var b=!1;return g(),a.utils.arrayForEach(f(),function(a){!a.isValid()&&a.isModified()&&(b=!0)}),b},g},formatMessage:function(b,c){return"function"==typeof b?b(c):b.replace(/\{0\}/gi,a.utils.unwrapObservable(c))},addRule:function(a,b){return a.extend({validatable:!0}),a.rules.push(b),a},addAnonymousRule:function(b,c){var e=d.newId();void 0===c.message&&(c.message="Error"),a.validation.rules[e]=c,a.validation.addRule(b,{rule:e,params:c.params})},addExtender:function(b){a.extenders[b]=function(c,e){return e.message||e.onlyIf?a.validation.addRule(c,{rule:b,message:e.message,params:d.isEmptyVal(e.params)?!0:e.params,condition:e.onlyIf}):a.validation.addRule(c,{rule:b,params:e})}},registerExtenders:function(){if(c.registerExtenders)for(var b in a.validation.rules)a.validation.rules.hasOwnProperty(b)&&(a.extenders[b]||a.validation.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=d.getConfigOptions(a).errorMessageClass,d.insertAfter(a,b),b},parseInputValidationAttributes:function(b,c){a.utils.arrayForEach(a.validation.configuration.html5Attributes,function(e){d.hasAttribute(b,e)&&a.validation.addRule(c(),{rule:e,params:b.getAttribute(e)||!0})});var e=b.getAttribute("type");a.utils.arrayForEach(a.validation.configuration.html5InputTypes,function(b){b===e&&a.validation.addRule(c(),{rule:"date"===b?"dateISO":b,params:!0})})},writeInputValidationAttributes:function(b,c){var d=c();if(d&&d.rules){var e=d.rules();a.utils.arrayForEach(a.validation.configuration.html5Attributes,function(c){var d,f=a.utils.arrayFirst(e,function(a){return a.rule.toLowerCase()===c.toLowerCase()});f&&(d=f.params,"pattern"===f.rule&&f.params instanceof RegExp&&(d=f.params.source),b.setAttribute(c,d))}),e=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var e=function(b,c){if(b&&c)for(var f in c)if(c.hasOwnProperty(f)){var g=c[f];if(b[f]){var h=b[f],i=a.utils.unwrapObservable(h),j={},k={};for(var l in g)g.hasOwnProperty(l)&&(a.validation.rules[l]?j[l]=g[l]:k[l]=g[l]);if(a.isObservable(h)&&h.extend(j),i&&d.isArray(i))for(var m=0;m0:!0)},message:"This field is required."},a.validation.rules.min={validator:function(b,c){return a.validation.utils.isEmptyVal(b)||b>=c},message:"Please enter a value greater than or equal to {0}."},a.validation.rules.max={validator:function(b,c){return a.validation.utils.isEmptyVal(b)||c>=b},message:"Please enter a value less than or equal to {0}."},a.validation.rules.minLength={validator:function(b,c){return a.validation.utils.isEmptyVal(b)||b.length>=c},message:"Please enter at least {0} characters."},a.validation.rules.maxLength={validator:function(b,c){return a.validation.utils.isEmptyVal(b)||b.length<=c},message:"Please enter no more than {0} characters."},a.validation.rules.pattern={validator:function(b,c){return a.validation.utils.isEmptyVal(b)||null!==b.toString().match(c)},message:"Please check this value."},a.validation.rules.step={validator:function(b,c){if(a.validation.utils.isEmptyVal(b)||"any"===c)return!0;var d=100*b%(100*c);return Math.abs(d)<1e-5||Math.abs(1-d)<1e-5},message:"The value must increment by {0}"},a.validation.rules.email={validator:function(b,c){return c?a.validation.utils.isEmptyVal(b)||c&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(b):!0},message:"Please enter a proper email address"},a.validation.rules.date={validator:function(b,c){return c?a.validation.utils.isEmptyVal(b)||c&&!/Invalid|NaN/.test(new Date(b)):!0},message:"Please enter a proper date"},a.validation.rules.dateISO={validator:function(b,c){return c?a.validation.utils.isEmptyVal(b)||c&&/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(b):!0},message:"Please enter a proper date"},a.validation.rules.number={validator:function(b,c){return c?a.validation.utils.isEmptyVal(b)||c&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(b):!0},message:"Please enter a number"},a.validation.rules.digit={validator:function(b,c){return c?a.validation.utils.isEmptyVal(b)||c&&/^\d+$/.test(b):!0},message:"Please enter a digit"},a.validation.rules.phoneUS={validator:function(b,c){return c?"string"!=typeof b?!1:a.validation.utils.isEmptyVal(b)?!0:(b=b.replace(/\s+/g,""),c&&b.length>9&&b.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number"},a.validation.rules.equal={validator:function(b,c){var d=c;return b===a.validation.utils.getValue(d)},message:"Values must equal"},a.validation.rules.notEqual={validator:function(b,c){var d=c;return b!==a.validation.utils.getValue(d)},message:"Please choose another value."},a.validation.rules.unique={validator:function(b,c){var d=a.validation.utils.getValue(c.collection),e=a.validation.utils.getValue(c.externalValue),f=0;return b&&d?(a.utils.arrayFilter(a.utils.unwrapObservable(d),function(a){b===(c.valueAccessor?c.valueAccessor(a):a)&&f++}),(void 0!==e&&b!==e?1:2)>f):!0},message:"Please make sure the value is unique."},function(){a.validation.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=a.validation.utils.getConfigOptions(b);if(d.parseInputAttributes&&a.validation.utils.async(function(){a.validation.parseInputValidationAttributes(b,c)}),d.insertMessages&&a.validation.utils.isValidatable(c())){var e=a.validation.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:c()},null,e,"replaceNode"):a.applyBindingsToNode(e,{validationMessage:c()})}d.writeInputAttributes&&a.validation.utils.isValidatable(c())&&a.validation.writeInputValidationAttributes(b,c),d.decorateElement&&a.validation.utils.isValidatable(c())&&a.applyBindingsToNode(b,{validationElement:c()})},update:function(){}}}(),a.validation.makeBindingHandlerValidatable("value"),a.validation.makeBindingHandlerValidatable("checked"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=a.validation.utils.getConfigOptions(b),f=(a.utils.unwrapObservable(d),!1),g=!1;d.extend({validatable:!0}),f=d.isModified(),g=d.isValid();var h=function(){return!e.messagesOnModified||f?g?null:d.error:null},i=function(){return!e.messagesOnModified||f?!g:!1};a.bindingHandlers.text.update(b,h),a.bindingHandlers.visible.update(b,i)}},a.bindingHandlers.validationElement={update:function(b,c){var d=c(),e=a.validation.utils.getConfigOptions(b),f=(a.utils.unwrapObservable(d),!1),g=!1;d.extend({validatable:!0}),f=d.isModified(),g=d.isValid();var h=function(){var a={},b=!e.decorateElementOnModified||f?!g:!1;return e.decorateElement||(b=!1),a[e.errorElementClass]=b,a};if(a.bindingHandlers.css.update(b,h),e.errorsAsTitle){a.validation.utils.getAttribute(b,"data-orig-title"),b.title,"true"===a.validation.utils.getAttribute(b,"data-orig-title");var i=function(){return!e.errorsAsTitleOnModified||f?g?{title:a.validation.utils.getOriginalElementTitle(b),"data-orig-title":null}:{title:d.error,"data-orig-title":a.validation.utils.getOriginalElementTitle(b)}:void 0};a.bindingHandlers.attr.update(b,i)}}},a.bindingHandlers.validationOptions=function(){return{init:function(b,c){var d=a.utils.unwrapObservable(c());if(d){var e=a.utils.extend({},a.validation.configuration);a.utils.extend(e,d),a.validation.utils.setDomData(b,e)}}}}(),a.extenders.validation=function(b,c){return a.utils.arrayForEach(a.validation.utils.isArray(c)?c:[c],function(c){a.validation.addAnonymousRule(b,c)}),b},a.extenders.validatable=function(b,c){if(c&&!a.validation.utils.isValidatable(b)){b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1);var d=a.computed(function(){return b(),b.rules(),a.validation.validateObservable(b),!0});b.isValid=a.computed(function(){return b.__valid__()}),b.setError=function(a){b.error(a),b.__valid__(!1)},b.clearError=function(){b.error(null),b.__valid__(!0)};var e=b.subscribe(function(){b.isModified(!0)});b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified._subscriptions.change=[],b.isValidating._subscriptions.change=[],b.__valid__._subscriptions.change=[],e.dispose(),d.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c===!1&&a.validation.utils.isValidatable(b)&&b._disposeValidation&&b._disposeValidation();return b},a.validation.validateObservable=function(b){for(var e,f,g=0,h=b.rules(),i=h.length;i>g;g++)if(f=h[g],!f.condition||f.condition())if(e=a.validation.rules[f.rule],e.async||f.async)d(b,e,f);else if(!c(b,e,f))return!1;return b.error(null),b.__valid__(!0),!0},a.validation.localize=function(b){var c;for(c in b)a.validation.rules.hasOwnProperty(c)&&(a.validation.rules[c].message=b[c])},a.applyBindingsWithValidation=function(b,c,d){var e,f,g=arguments.length;g>2?(e=c,f=d):2>g?e=document.body:arguments[1].nodeType?e=c:f=arguments[1],a.validation.init(),f&&a.validation.utils.setDomData(e,f),a.applyBindings(b,c)};var h=a.applyBindings;a.applyBindings=function(b,c){a.validation.init(),h(b,c)},a.validatedObservable=function(b){if(!a.validation.utils.isObject(b))return a.observable(b).extend({validatable:!0});var c=a.observable(b);return c.errors=a.validation.group(b),c.isValid=a.computed(function(){return 0===c.errors().length}),c}}); \ No newline at end of file diff --git a/Src/api.js b/Src/api.js index d82a6095..e3cda3d3 100644 --- a/Src/api.js +++ b/Src/api.js @@ -329,6 +329,51 @@ return ko.bindingHandlers['validationCore'].init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext); }; + }, + + // visit an objects properties and apply validation rules from a definition + setRules: function (target, definition) { + var setRules = function (target, definition) { + if (!target || !definition) { return; } + + for (var prop in definition) { + if (!definition.hasOwnProperty(prop)) { continue; } + var ruleDefinitions = definition[prop]; + + //check the target property exists and has a value + if (!target[prop]) { continue; } + var targetValue = target[prop], + unwrappedTargetValue = ko.utils.unwrapObservable(targetValue), + rules = {}, + nonRules = {}; + + for (var rule in ruleDefinitions) { + if (!ruleDefinitions.hasOwnProperty(rule)) { continue; } + if (ko.validation.rules[rule]) { + rules[rule] = ruleDefinitions[rule]; + } else { + nonRules[rule] = ruleDefinitions[rule]; + } + } + + //apply rules + if (ko.isObservable(targetValue)) { + targetValue.extend(rules); + } + + //then apply child rules + //if it's an array, apply rules to all children + if (unwrappedTargetValue && utils.isArray(unwrappedTargetValue)) { + for (var i = 0; i < unwrappedTargetValue.length; i++) { + setRules(unwrappedTargetValue[i], nonRules); + } + //otherwise, just apply to this property + } else { + setRules(unwrappedTargetValue, nonRules); + } + } + }; + setRules(target, definition); } }; }()); diff --git a/Tests/validation-tests.js b/Tests/validation-tests.js index 3aaa210b..41cc0905 100644 --- a/Tests/validation-tests.js +++ b/Tests/validation-tests.js @@ -2,6 +2,7 @@ module:false, equal:false, notEqual:false, + deepEqual: false, strictEqual:false, test:false, ok:false, @@ -1360,3 +1361,86 @@ asyncTest('Async Rule Is NOT Valid Test', function () { testObj.extend({ mustEqualAsync: 5 }); }); //#endregion + +//#region setRules Tests +module("setRules Tests"); + +test("setRules applies rules to all properties", function () { + var definition = { + property1: { + required: true, + min: 10, + max: 99, + ignoredDefinition: { required: true } + }, + child: { + property2: { + pattern: { + params: "^[a-z0-9].$", + message: "Only AlphaNumeric please" + } + }, + grandchild: { + property3: { + number: true + } + }, + ignoredDefinition: { required: true } + }, + nestedArray: { + property4: { email: true }, + ignoredDefinition: { required: true } + } + }; + + var target = { + property1: ko.observable(), + ignoredProperty: ko.observable(), + child: { + property2: ko.observable(), + ignoredProperty: ko.observable(), + grandchild: { + property3: ko.observable(), + ignoredProperty: ko.observable(), + } + }, + nestedArray: ko.observableArray([ + { property4: ko.observable(), ignoredProperty: ko.observable() }, + { property4: ko.observable(), ignoredProperty: ko.observable() }, + { property4: ko.observable(), ignoredProperty: ko.observable() } + ]) + }; + + ko.validation.setRules(target, definition); + + //check that all rules have been applied + deepEqual(target.property1.rules(), [ + { rule: "required", params: true }, + { rule: "min", params: 10 }, + { rule: "max", params: 99 } + ]); + + deepEqual(target.child.property2.rules(), [ + { rule: "pattern", message: "Only AlphaNumeric please", params: "^[a-z0-9].$", condition: undefined } + ]); + + deepEqual(target.child.grandchild.property3.rules(), [ + { rule: "number", params: true } + ]); + + for (var i = 0; i < target.nestedArray.length; i) { + deepEqual(target.nestedArray[i].property3.rules(), [ + { rule: "email", params: true } + ]); + } + + //check that ignored properties have not had rules added + ok(!target.ignoredProperty.rules); + ok(!target.child.ignoredProperty.rules); + ok(!target.child.grandchild.ignoredProperty.rules); + ok(!target.nestedArray()[0].ignoredProperty.rules); + ok(!target.nestedArray()[1].ignoredProperty.rules); + ok(!target.nestedArray()[2].ignoredProperty.rules); +}); + +//#endregion \ No newline at end of file From 4b7d9e4971b30c076117402686a49a5517680eb7 Mon Sep 17 00:00:00 2001 From: Steve Greatrex Date: Fri, 18 Oct 2013 21:19:36 +0100 Subject: [PATCH 037/165] Fixed whitespace issues --- Tests/validation-tests.js | 126 +++++++++++++++++++------------------- 1 file changed, 63 insertions(+), 63 deletions(-) diff --git a/Tests/validation-tests.js b/Tests/validation-tests.js index 41cc0905..8796547a 100644 --- a/Tests/validation-tests.js +++ b/Tests/validation-tests.js @@ -1366,81 +1366,81 @@ asyncTest('Async Rule Is NOT Valid Test', function () { module("setRules Tests"); test("setRules applies rules to all properties", function () { - var definition = { - property1: { - required: true, - min: 10, - max: 99, - ignoredDefinition: { required: true } - }, - child: { - property2: { - pattern: { - params: "^[a-z0-9].$", - message: "Only AlphaNumeric please" - } - }, - grandchild: { - property3: { - number: true - } - }, - ignoredDefinition: { required: true } - }, - nestedArray: { - property4: { email: true }, - ignoredDefinition: { required: true } - } - }; - - var target = { - property1: ko.observable(), - ignoredProperty: ko.observable(), - child: { - property2: ko.observable(), - ignoredProperty: ko.observable(), - grandchild: { - property3: ko.observable(), - ignoredProperty: ko.observable(), - } - }, - nestedArray: ko.observableArray([ + var definition = { + property1: { + required: true, + min: 10, + max: 99, + ignoredDefinition: { required: true } + }, + child: { + property2: { + pattern: { + params: "^[a-z0-9].$", + message: "Only AlphaNumeric please" + } + }, + grandchild: { + property3: { + number: true + } + }, + ignoredDefinition: { required: true } + }, + nestedArray: { + property4: { email: true }, + ignoredDefinition: { required: true } + } + }; + + var target = { + property1: ko.observable(), + ignoredProperty: ko.observable(), + child: { + property2: ko.observable(), + ignoredProperty: ko.observable(), + grandchild: { + property3: ko.observable(), + ignoredProperty: ko.observable(), + } + }, + nestedArray: ko.observableArray([ { property4: ko.observable(), ignoredProperty: ko.observable() }, { property4: ko.observable(), ignoredProperty: ko.observable() }, { property4: ko.observable(), ignoredProperty: ko.observable() } - ]) - }; + ]) + }; - ko.validation.setRules(target, definition); + ko.validation.setRules(target, definition); - //check that all rules have been applied - deepEqual(target.property1.rules(), [ + //check that all rules have been applied + deepEqual(target.property1.rules(), [ { rule: "required", params: true }, { rule: "min", params: 10 }, { rule: "max", params: 99 } - ]); + ]); - deepEqual(target.child.property2.rules(), [ + deepEqual(target.child.property2.rules(), [ { rule: "pattern", message: "Only AlphaNumeric please", params: "^[a-z0-9].$", condition: undefined } - ]); + ]); - deepEqual(target.child.grandchild.property3.rules(), [ + deepEqual(target.child.grandchild.property3.rules(), [ { rule: "number", params: true } - ]); - - for (var i = 0; i < target.nestedArray.length; i) { - deepEqual(target.nestedArray[i].property3.rules(), [ - { rule: "email", params: true } - ]); - } - - //check that ignored properties have not had rules added - ok(!target.ignoredProperty.rules); - ok(!target.child.ignoredProperty.rules); - ok(!target.child.grandchild.ignoredProperty.rules); - ok(!target.nestedArray()[0].ignoredProperty.rules); - ok(!target.nestedArray()[1].ignoredProperty.rules); - ok(!target.nestedArray()[2].ignoredProperty.rules); + ]); + + for (var i = 0; i < target.nestedArray.length; i) { + deepEqual(target.nestedArray[i].property3.rules(), [ + { rule: "email", params: true } + ]); + } + + //check that ignored properties have not had rules added + ok(!target.ignoredProperty.rules); + ok(!target.child.ignoredProperty.rules); + ok(!target.child.grandchild.ignoredProperty.rules); + ok(!target.nestedArray()[0].ignoredProperty.rules); + ok(!target.nestedArray()[1].ignoredProperty.rules); + ok(!target.nestedArray()[2].ignoredProperty.rules); }); //#endregion \ No newline at end of file From eefad889836a1900f044967728d292ea8934f696 Mon Sep 17 00:00:00 2001 From: Steve Greatrex Date: Fri, 18 Oct 2013 21:56:59 +0100 Subject: [PATCH 038/165] Fixed lint issue --- Dist/knockout.validation.min.js | 8 ++++++++ Tests/validation-ui-tests.js | 5 +++-- 2 files changed, 11 insertions(+), 2 deletions(-) create mode 100644 Dist/knockout.validation.min.js diff --git a/Dist/knockout.validation.min.js b/Dist/knockout.validation.min.js new file mode 100644 index 00000000..9b250687 --- /dev/null +++ b/Dist/knockout.validation.min.js @@ -0,0 +1,8 @@ +/*============================================================================= + Author: Eric M. Barnard - @ericmbarnard + License: MIT (http://opensource.org/licenses/mit-license.php) + + Description: Validation Library for KnockoutJS +=============================================================================== +*/ +!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(b,c,d){return c.validator(b(),void 0===d.params?!0:d.params)?!0:(b.error(a.validation.formatMessage(d.message||c.message,d.params)),b.__valid__(!1),!1)}function d(b,c,d){b.isValidating(!0);var e=function(e){var f=!1,g="";return b.__valid__()?(e.message?(f=e.isValid,g=e.message):f=e,f||(b.error(a.validation.formatMessage(g||d.message||c.message,d.params)),b.__valid__(f)),b.isValidating(!1),void 0):(b.isValidating(!1),void 0)};c.validator(b(),d.params||!0,e)}if(void 0===typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var e={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",grouping:{deep:!1,observable:!0}},f=a.utils.extend({},e);f.html5Attributes=["required","pattern","min","max","step"],f.html5InputTypes=["email","number","date"],f.reset=function(){a.utils.extend(f,e)},a.validation.configuration=f,a.validation.utils=function(){var b=(new Date).getTime(),c={},d="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return a&&a.rules&&a.isValid&&a.isModified},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return b+=1},getConfigOptions:function(b){var c=a.validation.utils.contextFor(b);return c||a.validation.configuration},setDomData:function(b,e){var f=b[d];f||(b[d]=f=a.validation.utils.newId()),c[f]=e},getDomData:function(a){var b=a[d];return b?c[b]:void 0},contextFor:function(b){switch(b.nodeType){case 1:case 8:var c=a.validation.utils.getDomData(b);if(c)return c;if(b.parentNode)return a.validation.utils.contextFor(b.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(b){var c=a.validation.utils.getAttribute(b,"data-orig-title"),d=b.title,e=a.validation.utils.hasAttribute(b,"data-orig-title");return e?c:d},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)}}}();var g=function(){var b=0,c=a.validation.configuration,d=a.validation.utils;return{init:function(d,e){b>0&&!e||(d=d||{},d.errorElementClass=d.errorElementClass||d.errorClass||c.errorElementClass,d.errorMessageClass=d.errorMessageClass||d.errorClass||c.errorMessageClass,a.utils.extend(c,d),c.registerExtenders&&a.validation.registerExtenders(),b=1)},configure:function(b){a.validation.init(b)},reset:a.validation.configuration.reset,group:function(b,e){e=a.utils.extend(a.utils.extend({},c.grouping),e);var f=a.observableArray([]),g=null,h=function i(b,c){var g=[],h=a.utils.unwrapObservable(b);c=void 0!==c?c:e.deep?1:-1,a.isObservable(b)&&(b.isValid||b.extend({validatable:!0}),f.push(b)),h&&(d.isArray(h)?g=h:d.isObject(h)&&(g=d.values(h))),0!==c&&a.utils.arrayForEach(g,function(a){a&&!a.nodeType&&i(a,c+1)})};return e.observable?(h(b),g=a.computed(function(){var b=[];return a.utils.arrayForEach(f(),function(a){a.isValid()||b.push(a.error)}),b})):g=function(){var c=[];return f([]),h(b),a.utils.arrayForEach(f(),function(a){a.isValid()||c.push(a.error)}),c},g.showAllMessages=function(b){void 0===b&&(b=!0),g(),a.utils.arrayForEach(f(),function(a){a.isModified(b)})},b.errors=g,b.isValid=function(){return 0===b.errors().length},b.isAnyMessageShown=function(){var b=!1;return g(),a.utils.arrayForEach(f(),function(a){!a.isValid()&&a.isModified()&&(b=!0)}),b},g},formatMessage:function(b,c){return"function"==typeof b?b(c):b.replace(/\{0\}/gi,a.utils.unwrapObservable(c))},addRule:function(a,b){return a.extend({validatable:!0}),a.rules.push(b),a},addAnonymousRule:function(b,c){var e=d.newId();void 0===c.message&&(c.message="Error"),a.validation.rules[e]=c,a.validation.addRule(b,{rule:e,params:c.params})},addExtender:function(b){a.extenders[b]=function(c,e){return e.message||e.onlyIf?a.validation.addRule(c,{rule:b,message:e.message,params:d.isEmptyVal(e.params)?!0:e.params,condition:e.onlyIf}):a.validation.addRule(c,{rule:b,params:e})}},registerExtenders:function(){if(c.registerExtenders)for(var b in a.validation.rules)a.validation.rules.hasOwnProperty(b)&&(a.extenders[b]||a.validation.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=d.getConfigOptions(a).errorMessageClass,d.insertAfter(a,b),b},parseInputValidationAttributes:function(b,c){a.utils.arrayForEach(a.validation.configuration.html5Attributes,function(e){d.hasAttribute(b,e)&&a.validation.addRule(c(),{rule:e,params:b.getAttribute(e)||!0})});var e=b.getAttribute("type");a.utils.arrayForEach(a.validation.configuration.html5InputTypes,function(b){b===e&&a.validation.addRule(c(),{rule:"date"===b?"dateISO":b,params:!0})})},writeInputValidationAttributes:function(b,c){var d=c();if(d&&d.rules){var e=d.rules();a.utils.arrayForEach(a.validation.configuration.html5Attributes,function(c){var d,f=a.utils.arrayFirst(e,function(a){return a.rule.toLowerCase()===c.toLowerCase()});f&&(d=f.params,"pattern"===f.rule&&f.params instanceof RegExp&&(d=f.params.source),b.setAttribute(c,d))}),e=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}}}}();a.utils.extend(a.validation,g),a.validation.rules={},a.validation.rules.required={validator:function(a,b){var c,d=/^\s+|\s+$/g;return void 0===a||null===a?!b:(c=a,"string"==typeof a&&(c=a.replace(d,"")),b?(c+"").length>0:!0)},message:"This field is required."},a.validation.rules.min={validator:function(b,c){return a.validation.utils.isEmptyVal(b)||b>=c},message:"Please enter a value greater than or equal to {0}."},a.validation.rules.max={validator:function(b,c){return a.validation.utils.isEmptyVal(b)||c>=b},message:"Please enter a value less than or equal to {0}."},a.validation.rules.minLength={validator:function(b,c){return a.validation.utils.isEmptyVal(b)||b.length>=c},message:"Please enter at least {0} characters."},a.validation.rules.maxLength={validator:function(b,c){return a.validation.utils.isEmptyVal(b)||b.length<=c},message:"Please enter no more than {0} characters."},a.validation.rules.pattern={validator:function(b,c){return a.validation.utils.isEmptyVal(b)||null!==b.toString().match(c)},message:"Please check this value."},a.validation.rules.step={validator:function(b,c){if(a.validation.utils.isEmptyVal(b)||"any"===c)return!0;var d=100*b%(100*c);return Math.abs(d)<1e-5||Math.abs(1-d)<1e-5},message:"The value must increment by {0}"},a.validation.rules.email={validator:function(b,c){return c?a.validation.utils.isEmptyVal(b)||c&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(b):!0},message:"Please enter a proper email address"},a.validation.rules.date={validator:function(b,c){return c?a.validation.utils.isEmptyVal(b)||c&&!/Invalid|NaN/.test(new Date(b)):!0},message:"Please enter a proper date"},a.validation.rules.dateISO={validator:function(b,c){return c?a.validation.utils.isEmptyVal(b)||c&&/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(b):!0},message:"Please enter a proper date"},a.validation.rules.number={validator:function(b,c){return c?a.validation.utils.isEmptyVal(b)||c&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(b):!0},message:"Please enter a number"},a.validation.rules.digit={validator:function(b,c){return c?a.validation.utils.isEmptyVal(b)||c&&/^\d+$/.test(b):!0},message:"Please enter a digit"},a.validation.rules.phoneUS={validator:function(b,c){return c?a.validation.utils.isEmptyVal(b)?!0:"string"!=typeof b?!1:(b=b.replace(/\s+/g,""),c&&b.length>9&&b.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number"},a.validation.rules.equal={validator:function(b,c){var d=c;return b===a.validation.utils.getValue(d)},message:"Values must equal"},a.validation.rules.notEqual={validator:function(b,c){var d=c;return b!==a.validation.utils.getValue(d)},message:"Please choose another value."},a.validation.rules.unique={validator:function(b,c){var d=a.validation.utils.getValue(c.collection),e=a.validation.utils.getValue(c.externalValue),f=0;return b&&d?(a.utils.arrayFilter(a.utils.unwrapObservable(d),function(a){b===(c.valueAccessor?c.valueAccessor(a):a)&&f++}),(void 0!==e&&b!==e?1:2)>f):!0},message:"Please make sure the value is unique."},function(){a.validation.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=a.validation.utils.getConfigOptions(b);if(d.parseInputAttributes&&a.validation.utils.async(function(){a.validation.parseInputValidationAttributes(b,c)}),d.insertMessages&&a.validation.utils.isValidatable(c())){var e=a.validation.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:c()},null,e,"replaceNode"):a.applyBindingsToNode(e,{validationMessage:c()})}d.writeInputAttributes&&a.validation.utils.isValidatable(c())&&a.validation.writeInputValidationAttributes(b,c),d.decorateElement&&a.validation.utils.isValidatable(c())&&a.applyBindingsToNode(b,{validationElement:c()})},update:function(){}}}(),a.validation.makeBindingHandlerValidatable("value"),a.validation.makeBindingHandlerValidatable("checked"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=a.validation.utils.getConfigOptions(b),f=(a.utils.unwrapObservable(d),!1),g=!1;d.extend({validatable:!0}),f=d.isModified(),g=d.isValid();var h=function(){return!e.messagesOnModified||f?g?null:d.error:null},i=function(){return!e.messagesOnModified||f?!g:!1};a.bindingHandlers.text.update(b,h),a.bindingHandlers.visible.update(b,i)}},a.bindingHandlers.validationElement={update:function(b,c){var d=c(),e=a.validation.utils.getConfigOptions(b),f=(a.utils.unwrapObservable(d),!1),g=!1;d.extend({validatable:!0}),f=d.isModified(),g=d.isValid();var h=function(){var a={},b=!e.decorateElementOnModified||f?!g:!1;return e.decorateElement||(b=!1),a[e.errorElementClass]=b,a};if(a.bindingHandlers.css.update(b,h),e.errorsAsTitle){a.validation.utils.getAttribute(b,"data-orig-title"),b.title,"true"===a.validation.utils.getAttribute(b,"data-orig-title");var i=function(){return!e.errorsAsTitleOnModified||f?g?{title:a.validation.utils.getOriginalElementTitle(b),"data-orig-title":null}:{title:d.error,"data-orig-title":a.validation.utils.getOriginalElementTitle(b)}:void 0};a.bindingHandlers.attr.update(b,i)}}},a.bindingHandlers.validationOptions=function(){return{init:function(b,c){var d=a.utils.unwrapObservable(c());if(d){var e=a.utils.extend({},a.validation.configuration);a.utils.extend(e,d),a.validation.utils.setDomData(b,e)}}}}(),a.extenders.validation=function(b,c){return a.utils.arrayForEach(a.validation.utils.isArray(c)?c:[c],function(c){a.validation.addAnonymousRule(b,c)}),b},a.extenders.validatable=function(b,c){if(c&&!a.validation.utils.isValidatable(b)){b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1);var d=a.computed(function(){return b(),b.rules(),a.validation.validateObservable(b),!0});b.isValid=a.computed(function(){return b.__valid__()}),b.setError=function(a){b.error(a),b.__valid__(!1)},b.clearError=function(){b.error(null),b.__valid__(!0)};var e=b.subscribe(function(){b.isModified(!0)});b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified._subscriptions.change=[],b.isValidating._subscriptions.change=[],b.__valid__._subscriptions.change=[],e.dispose(),d.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c===!1&&a.validation.utils.isValidatable(b)&&b._disposeValidation&&b._disposeValidation();return b},a.validation.validateObservable=function(b){for(var e,f,g=0,h=b.rules(),i=h.length;i>g;g++)if(f=h[g],!f.condition||f.condition())if(e=a.validation.rules[f.rule],e.async||f.async)d(b,e,f);else if(!c(b,e,f))return!1;return b.error(null),b.__valid__(!0),!0},a.validation.localize=function(b){var c;for(c in b)a.validation.rules.hasOwnProperty(c)&&(a.validation.rules[c].message=b[c])},a.applyBindingsWithValidation=function(b,c,d){var e,f,g=arguments.length;g>2?(e=c,f=d):2>g?e=document.body:arguments[1].nodeType?e=c:f=arguments[1],a.validation.init(),f&&a.validation.utils.setDomData(e,f),a.applyBindings(b,c)};var h=a.applyBindings;a.applyBindings=function(b,c){a.validation.init(),h(b,c)},a.validatedObservable=function(b){if(!a.validation.utils.isObject(b))return a.observable(b).extend({validatable:!0});var c=a.observable(b);return c.errors=a.validation.group(b),c.isValid=a.computed(function(){return 0===c.errors().length}),c}}); \ No newline at end of file diff --git a/Tests/validation-ui-tests.js b/Tests/validation-ui-tests.js index a488759b..c7efb22a 100644 --- a/Tests/validation-ui-tests.js +++ b/Tests/validation-ui-tests.js @@ -628,8 +628,9 @@ test("HTML5 Input types", function () { vm.invalidEmail.rules().length > 0 && vm.invalidDate.rules().length > 0 && vm.invalidNumber.rules().length > 0; - if (validatorsReady) - runAssertions(); + if (validatorsReady) { + runAssertions(); + } }, 1); function runAssertions() From fdd75157485f91198f9d9e9dc6867b378b897033 Mon Sep 17 00:00:00 2001 From: gongdo Date: Tue, 22 Oct 2013 18:06:55 +0900 Subject: [PATCH 039/165] Add Korean resource --- Localization/ko-KR.js | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Localization/ko-KR.js diff --git a/Localization/ko-KR.js b/Localization/ko-KR.js new file mode 100644 index 00000000..98563678 --- /dev/null +++ b/Localization/ko-KR.js @@ -0,0 +1,39 @@ +/// + +/************************************************ +* This is an example localization page. All of these +* messages are the default messages for ko.validation +* +* Currently ko.validation only does a single parameter replacement +* on your message (indicated by the {0}). +* +* The parameter that you provide in your validation extender +* is what is passed to your message to do the {0} replacement. +* +* eg: myProperty.extend({ minLength: 5 }); +* ... will provide a message of "Please enter at least 5 characters" +* when validated +* +* This message replacement obviously only works with primitives +* such as numbers and strings. We do not stringify complex objects +* or anything like that currently. +*/ + +ko.validation.localize({ + required: '필수 입력항목입니다.', + min: '{0}보다 큰 값을 입력해 주십시오.', + max: '{0}보다 작은 값을 입력해 주십시오.', + minLength: '{0}글자 이상으로 입력해 주십시오.', + maxLength: '{0}글자 이하로 입력해 주십시오.', + pattern: '입력한 값의 형식이 올바르지 않습니다.', + step: '이 값은 반드시 {0}씩 증가해야 합니다.', + email:'올바른 이메일 주소 형식이 아닙니다.', + date: '올바른 날짜 형식이 아닙니다.', + dateISO: '올바른 날짜 형식이 아닙니다.', + number: '숫자를 입력해 주십시오.', + digit: '숫자를 입력해 주십시오.', + phoneUS: '올바른 전화번호 형식이 아닙니다.', + equal: '같은 값을 입력해 주십시오.', + notEqual: '다른 값을 선택해 주십시오.', + unique: '고유한 값인지 확인해 주십시오.' +}); From e48950df578b72c6f5f19d68c5db810bf6fc20bf Mon Sep 17 00:00:00 2001 From: Sergiy Stotskiy Date: Wed, 23 Oct 2013 11:25:32 +0300 Subject: [PATCH 040/165] This commit fixes #342 issue. --- Src/ko.validation.start.frag | 6 +++++- gruntfile.js | 39 +++++++++++++++++++++--------------- 2 files changed, 28 insertions(+), 17 deletions(-) diff --git a/Src/ko.validation.start.frag b/Src/ko.validation.start.frag index 00b3db87..868eb834 100644 --- a/Src/ko.validation.start.frag +++ b/Src/ko.validation.start.frag @@ -18,4 +18,8 @@ if (typeof (ko) === undefined) { throw 'Knockout is required, please ensure it is loaded before loading this validation plug-in'; } // create our namespace object - ko.validation = exports; \ No newline at end of file + ko.validation = exports; + + var kv = ko.validation; + var koUtils = ko.utils; + var unwrap = koUtils.unwrapObservable; diff --git a/gruntfile.js b/gruntfile.js index e6092265..793275ac 100644 --- a/gruntfile.js +++ b/gruntfile.js @@ -15,32 +15,39 @@ module.exports = function (grunt) { concat: { options: { separator: ";", - banner: "<%= meta.banner %>" + banner: "<%= meta.banner %>", + process: function (src, filepath) { + return src + .replace(/ko\.validation\./g, 'kv.') + .replace(/ko\.utils\.unwrapObservable/g, 'unwrap') + .replace(/ko\.utils\./g, 'koUtils.'); + } }, dist: { src: [ "<%= meta.banner %>", - "src/ko.validation.start.frag", - "src/configuration.js", - "src/utils.js", - "src/api.js", - "src/rules.js", - "src/bindingHandlers.js", - "src/extenders.js", - "src/localization.js", - "src/ko.extensions.js", - "src/ko.validation.end.frag", + "Src/ko.validation.start.frag", + "Src/configuration.js", + "Src/utils.js", + "Src/api.js", + "Src/rules.js", + "Src/bindingHandlers.js", + "Src/extenders.js", + "Src/localization.js", + "Src/ko.extensions.js", + "Src/ko.validation.end.frag", ], - dest: "dist/<%= pkg.name %>.js" + dest: "Dist/<%= pkg.name %>.js" } }, uglify: { options: { - banner: "<%= meta.banner %>" + banner: "<%= meta.banner %>", + report: "min" }, dist: { files: { - "dist/<%= pkg.name %>.min.js": ["<%= concat.dist.dest %>"] + "Dist/<%= pkg.name %>.min.js": ["<%= concat.dist.dest %>"] } } }, @@ -48,12 +55,12 @@ module.exports = function (grunt) { files: ["Tests/test-runner.htm"] }, jshint: { - files: ["src/**/*.js", "Tests/*.js"], + files: ["Src/**/*.js", "Tests/*.js"], options: grunt.file.readJSON(".jshintrc"), }, watch: { clear: { - files: ["src/**/*.js", "Tests/*.js"], + files: ["Src/**/*.js", "Tests/*.js"], tasks: ["clear", "test"] } } From a4059405f3a9c56158e64859e9cfbbb2f8d00c69 Mon Sep 17 00:00:00 2001 From: Sergiy Stotskiy Date: Wed, 23 Oct 2013 12:24:44 +0300 Subject: [PATCH 041/165] Added few more minifications --- Src/ko.validation.start.frag | 2 ++ gruntfile.js | 2 ++ 2 files changed, 4 insertions(+) diff --git a/Src/ko.validation.start.frag b/Src/ko.validation.start.frag index 868eb834..995832e1 100644 --- a/Src/ko.validation.start.frag +++ b/Src/ko.validation.start.frag @@ -23,3 +23,5 @@ var kv = ko.validation; var koUtils = ko.utils; var unwrap = koUtils.unwrapObservable; + var forEach = koUtils.arrayForEach; + var extend = koUtils.extend; diff --git a/gruntfile.js b/gruntfile.js index 793275ac..91c07725 100644 --- a/gruntfile.js +++ b/gruntfile.js @@ -19,6 +19,8 @@ module.exports = function (grunt) { process: function (src, filepath) { return src .replace(/ko\.validation\./g, 'kv.') + .replace(/ko\.utils\.arrayForEach/g, 'forEach') + .replace(/ko\.utils\.extend/g, 'extend') .replace(/ko\.utils\.unwrapObservable/g, 'unwrap') .replace(/ko\.utils\./g, 'koUtils.'); } From c9815c715a18f440030cbe483ea79eb7084b069b Mon Sep 17 00:00:00 2001 From: Sergiy Stotskiy Date: Wed, 23 Oct 2013 14:01:16 +0300 Subject: [PATCH 042/165] It fixes #344 --- Src/bindingHandlers.js | 13 ++++---- Src/configuration.js | 5 ++- Src/extenders.js | 61 +++++++++++++++++++--------------- Src/ko.extensions.js | 7 ++-- Tests/validation-tests.js | 70 +++++++++++++++++++++++++++++++++------ gruntfile.js | 2 ++ 6 files changed, 111 insertions(+), 47 deletions(-) diff --git a/Src/bindingHandlers.js b/Src/bindingHandlers.js index 6a69fe1a..6fef550d 100644 --- a/Src/bindingHandlers.js +++ b/Src/bindingHandlers.js @@ -6,6 +6,7 @@ ko.bindingHandlers['validationCore'] = (function () { return { init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { var config = ko.validation.utils.getConfigOptions(element); + var observable = valueAccessor(); // parse html5 input validation attributes, optional feature if (config.parseInputAttributes) { @@ -13,28 +14,28 @@ ko.bindingHandlers['validationCore'] = (function () { } // if requested insert message element and apply bindings - if (config.insertMessages && ko.validation.utils.isValidatable(valueAccessor())) { + if (config.insertMessages && ko.validation.utils.isValidatable(observable)) { // insert the var validationMessageElement = ko.validation.insertValidationMessage(element); // if we're told to use a template, make sure that gets rendered if (config.messageTemplate) { - ko.renderTemplate(config.messageTemplate, { field: valueAccessor() }, null, validationMessageElement, 'replaceNode'); + ko.renderTemplate(config.messageTemplate, { field: observable }, null, validationMessageElement, 'replaceNode'); } else { - ko.applyBindingsToNode(validationMessageElement, { validationMessage: valueAccessor() }); + ko.applyBindingsToNode(validationMessageElement, { validationMessage: observable }); } } // write the html5 attributes if indicated by the config - if (config.writeInputAttributes && ko.validation.utils.isValidatable(valueAccessor())) { + if (config.writeInputAttributes && ko.validation.utils.isValidatable(observable)) { ko.validation.writeInputValidationAttributes(element, valueAccessor); } // if requested, add binding to decorate element - if (config.decorateElement && ko.validation.utils.isValidatable(valueAccessor())) { - ko.applyBindingsToNode(element, { validationElement: valueAccessor() }); + if (config.decorateElement && ko.validation.utils.isValidatable(observable)) { + ko.applyBindingsToNode(element, { validationElement: observable }); } }, diff --git a/Src/configuration.js b/Src/configuration.js index 6572d7e0..8f3ca5a2 100644 --- a/Src/configuration.js +++ b/Src/configuration.js @@ -17,6 +17,9 @@ var defaults = { grouping: { deep: false, //by default grouping is shallow observable: true //and using observables + }, + validate: { + // throttle: 10 } }; @@ -30,4 +33,4 @@ configuration.reset = function () { ko.utils.extend(configuration, defaults); }; -ko.validation.configuration = configuration; \ No newline at end of file +ko.validation.configuration = configuration; diff --git a/Src/extenders.js b/Src/extenders.js index 15e4589a..461f5606 100644 --- a/Src/extenders.js +++ b/Src/extenders.js @@ -27,8 +27,20 @@ ko.extenders['validation'] = function (observable, rules) { // allow single rule // // 2. test.extend({validatable: false}); // this will remove the validation properties from the Observable object should you need to do that. -ko.extenders['validatable'] = function (observable, enable) { - if (enable && !ko.validation.utils.isValidatable(observable)) { +ko.extenders['validatable'] = function (observable, options) { + if (!ko.validation.utils.isObject(options)) { + options = { enable: options }; + } + + if (!('enable' in options)) { + options.enable = true; + } + + if (options.enable && !ko.validation.utils.isValidatable(observable)) { + var config = ko.validation.configuration.validate || {}; + var validationOptions = { + throttleEvaluation : options.throttle || config.throttle + }; observable.error = ko.observable(null); // holds the error message, we only need one since we stop processing validators when one is invalid @@ -46,21 +58,8 @@ ko.extenders['validatable'] = function (observable, enable) { observable.isModified = ko.observable(false); - // we use a computed here to ensure that anytime a dependency changes, the - // validation logic evaluates - var h_obsValidationTrigger = ko.computed(function () { - var obs = observable(), - ruleContexts = observable.rules(); - - ko.validation.validateObservable(observable); - - return true; - }); - // a semi-protected observable - observable.isValid = ko.computed(function () { - return observable.__valid__(); - }); + observable.isValid = ko.computed(observable.__valid__); //manually set error state observable.setError = function (error) { @@ -79,6 +78,21 @@ ko.extenders['validatable'] = function (observable, enable) { observable.isModified(true); }); + // we use a computed here to ensure that anytime a dependency changes, the + // validation logic evaluates + var h_obsValidationTrigger = ko.computed(ko.utils.extend({ + read: function () { + var obs = observable(), + ruleContexts = observable.rules(); + + ko.validation.validateObservable(observable); + + return true; + } + }, validationOptions)); + + ko.utils.extend(h_obsValidationTrigger, validationOptions); + observable._disposeValidation = function () { //first dispose of the subscriptions observable.isValid.dispose(); @@ -96,11 +110,8 @@ ko.extenders['validatable'] = function (observable, enable) { delete observable['__valid__']; delete observable['isModified']; }; - } else if (enable === false && ko.validation.utils.isValidatable(observable)) { - - if (observable._disposeValidation) { - observable._disposeValidation(); - } + } else if (options.enable === false && observable._disposeValidation) { + observable._disposeValidation(); } return observable; }; @@ -110,8 +121,7 @@ function validateSync(observable, rule, ctx) { if (!rule.validator(observable(), ctx.params === undefined ? true : ctx.params)) { // default param is true, eg. required = true //not valid, so format the error message and stick it in the 'error' variable - observable.error(ko.validation.formatMessage(ctx.message || rule.message, ctx.params)); - observable.__valid__(false); + observable.setError(ko.validation.formatMessage(ctx.message || rule.message, ctx.params)); return false; } else { return true; @@ -187,7 +197,6 @@ ko.validation.validateObservable = function (observable) { } } //finally if we got this far, make the observable valid again! - observable.error(null); - observable.__valid__(true); + observable.clearError(); return true; -}; \ No newline at end of file +}; diff --git a/Src/ko.extensions.js b/Src/ko.extensions.js index 5aabb595..0702d8ea 100644 --- a/Src/ko.extensions.js +++ b/Src/ko.extensions.js @@ -35,10 +35,11 @@ ko.validatedObservable = function (initialValue) { if (!ko.validation.utils.isObject(initialValue)) { return ko.observable(initialValue).extend({ validatable: true }); } var obsv = ko.observable(initialValue); + obsv.isValid = ko.observable(); obsv.errors = ko.validation.group(initialValue); - obsv.isValid = ko.computed(function () { - return obsv.errors().length === 0; + obsv.errors.subscribe(function (errors) { + obsv.isValid(errors.length === 0); }); return obsv; -}; \ No newline at end of file +}; diff --git a/Tests/validation-tests.js b/Tests/validation-tests.js index e374f5a7..7dc8f39e 100644 --- a/Tests/validation-tests.js +++ b/Tests/validation-tests.js @@ -1,9 +1,9 @@ -/*global - module:false, - equal:false, +/*global + module:false, + equal:false, notEqual:false, strictEqual:false, - test:false, + test:false, ok:false, asyncTest:false, start: false, @@ -59,7 +59,7 @@ test('Issue #90 - "required: false" doesnt force validation', function () { .extend({ required: false }); equal(testObj.isValid(), true, 'testObj is valid without value'); - + testObj('blah'); equal(testObj.isValid(), true, 'testObj is valid with value'); @@ -372,7 +372,7 @@ test('Pattern validation mismatches numbers', function () { test('Pattern validation doesn\'t break with non-string values', function () { var testObj = ko.observable('') .extend({ pattern: '^$' }); - + testObj(12345); testObj.isValid(); @@ -610,7 +610,7 @@ test('Object is Valid when empty string is present - Preserves Optional Properti }); test('Object is Valid and isValid returns True', function () { - var testObj = ko.observable('').extend({ dateISO: true }); + var testObj = ko.observable('').extend({ dateISO: true }); testObj('2011-11-18'); @@ -878,7 +878,7 @@ test( 'Issue #81 - Dynamic messages', function () { var CustomRule = function () { var self = this; - + this.message = 'before'; this.params = 0; @@ -928,9 +928,9 @@ test('Object is Valid and isValid returns True', function () { }); test('Object is Valid and isValid returns True', function () { - var testObj = ko.observable().extend({ + var testObj = ko.observable().extend({ required: true, - minLength: 2, + minLength: 2, pattern: { message: 'It must contain some', params: 'some' @@ -1212,7 +1212,7 @@ test('Issue #31 - Recursively Show All Messages', function () { ok(!vm.one.isModified(), "Level 1 is not modified"); ok(!vm.two.one.isModified(), "Level 2 is not modified"); ok(!vm.three.two.one.isModified(), "Level 3 is not modified"); - + // now show all the messages errors.showAllMessages(); @@ -1548,3 +1548,51 @@ asyncTest('Async Rule Is NOT Valid Test', function () { testObj.extend({ mustEqualAsync: 5 }); }); //#endregion + +//# validation process tests +module("Validation process", { + setup: function () { + var isStarted = false; + ko.validation._validateObservable = ko.validation.validateObservable; + ko.validation.validateObservable = function () { + ok(true, "Triggered only once"); + if (!isStarted) { + isStarted = true; + start(); + } + + return ko.validation._validateObservable.apply(this, arguments); + }; + }, + + teardown: function () { + ko.validation.validateObservable = ko.validation._validateObservable; + } +}); + +asyncTest("can be throttled using global configuration", function () { + expect(2); // one for initialization and when value changed + + ko.validation.init({ validate: { + throttle: 10 + }}, true); + + var observable = ko.observable().extend({ validatable: true }); + observable("1"); + observable.extend({ minLength: 2 }); + + ko.validation.init({ validate: {} }, true); +}); + +asyncTest("can be throttled using using local configuration", function () { + expect(2); // one for initialization and when value changed + + var observable = ko.observable().extend({ validatable: { + throttle: 10 + } }); + + observable.extend({ minLength: 2 }); + observable("1"); +}); + +//#endregion diff --git a/gruntfile.js b/gruntfile.js index 91c07725..41a26fd0 100644 --- a/gruntfile.js +++ b/gruntfile.js @@ -78,4 +78,6 @@ module.exports = function (grunt) { // Default task. grunt.registerTask("default", ["test", "uglify"]); grunt.registerTask("test", ["concat", "qunit", "jshint"]); + + grunt.registerTask("compile", ["concat", "qunit", "uglify"]); }; From 2b12aadada1a7b21760ad015b4d458fb0458c270 Mon Sep 17 00:00:00 2001 From: Sergiy Stotskiy Date: Fri, 25 Oct 2013 01:03:05 +0300 Subject: [PATCH 043/165] Removed unnecessary functions creations. Removed code duplications Conflicts: Src/api.js --- Src/api.js | 147 ++++++++++++++++++++++++++------------------------- Src/utils.js | 10 ++++ 2 files changed, 86 insertions(+), 71 deletions(-) diff --git a/Src/api.js b/Src/api.js index 8aa730ed..82ade75b 100644 --- a/Src/api.js +++ b/Src/api.js @@ -4,6 +4,65 @@ configuration = ko.validation.configuration, utils = ko.validation.utils; + + function traverseGraph(obj, options, level) { + var objValues = [], + val = ko.utils.unwrapObservable(obj); + + if (!options.flagged) { + options.flagged = []; + } + + if (!options.toValidate) { + options.toValidate = []; + } + + if (obj.__kv_traversed === true) { return; } + + if (options.deep) { + obj.__kv_traversed = true; + options.flagged.push(obj); + } + + //default level value depends on deep option. + level = (level !== undefined ? level : options.deep ? 1 : -1); + + // if object is observable then add it to the list + if (ko.isObservable(obj)) { + + //make sure it is validatable object + if (!obj.isValid) { obj.extend({ validatable: true }); } + options.toValidate.push(obj); + } + + //get list of values either from array or object but ignore non-objects + if (val && (utils.isArray(val) || utils.isObject(val))) { + objValues = val; + } + + //process recurisvely if it is deep grouping + if (level !== 0) { + utils.forEach(objValues, function (observable) { + + //but not falsy things and not HTML Elements + if (observable && !observable.nodeType) { + traverseGraph(observable, options, level + 1); + } + }); + } + } + + function collectErrors(array) { + var errors = []; + ko.utils.arrayForEach(array, function (observable) { + if (!observable.isValid()) { + errors.push(observable.error); + } + }); + return errors; + } + + return { //Call this on startup //any config can be overridden with the passed in options @@ -46,89 +105,34 @@ options = ko.utils.extend(ko.utils.extend({}, configuration.grouping), options); var validatables = ko.observableArray([]), - result = null, - flagged = [], - - dispose = function () { - if (options.deep) { - ko.utils.arrayForEach(flagged, function (obj) { - delete obj.__kv_traversed; - }); - } - }, - - //anonymous, immediate function to traverse objects hierarchically - //if !options.deep then it will stop on top level - traverse = function traverse(obj, level) { - var objValues = [], - val = ko.utils.unwrapObservable(obj); - - if (obj.__kv_traversed === true) { return; } - - if (options.deep) { - obj.__kv_traversed = true; - flagged.push(obj); - } - - //default level value depends on deep option. - level = (level !== undefined ? level : options.deep ? 1 : -1); - - // if object is observable then add it to the list - if (ko.isObservable(obj)) { - - //make sure it is validatable object - if (!obj.isValid) { obj.extend({ validatable: true }); } - validatables.push(obj); - } - - //get list of values either from array or object but ignore non-objects - if (val) { - if (utils.isArray(val)) { - objValues = val; - } else if (utils.isObject(val)) { - objValues = utils.values(val); - } - } - - //process recurisvely if it is deep grouping - if (level !== 0) { - ko.utils.arrayForEach(objValues, function (observable) { - - //but not falsy things and not HTML Elements - if (observable && !observable.nodeType) { traverse(observable, level + 1); } - }); - } - }; + result = null, + dispose = function () { + if (options.deep) { + ko.utils.arrayForEach(options.flagged, function (obj) { + delete obj.__kv_traversed; + }); + options.flagged.length = 0; + } + options.toValidate = []; + }; //if using observables then traverse structure once and add observables if (options.observable) { - - traverse(obj); + traverseGraph(obj, options); + validatables(options.toValidate); dispose(); result = ko.computed(function () { - var errors = []; - ko.utils.arrayForEach(validatables(), function (observable) { - if (!observable.isValid()) { - errors.push(observable.error); - } - }); - return errors; + return collectErrors(validatables()); }); } else { //if not using observables then every call to error() should traverse the structure result = function () { - var errors = []; - validatables([]); //clear validatables - traverse(obj); // and traverse tree again + traverseGraph(obj, options); // and traverse tree again + validatables(options.toValidate); dispose(); - ko.utils.arrayForEach(validatables(), function (observable) { - if (!observable.isValid()) { - errors.push(observable.error); - } - }); - return errors; + return collectErrors(validatables()); }; } @@ -348,6 +352,7 @@ }; } }; + }()); // expose api publicly diff --git a/Src/utils.js b/Src/utils.js index 247f8c07..347b0eba 100644 --- a/Src/utils.js +++ b/Src/utils.js @@ -97,6 +97,16 @@ async: function (expr) { if (window.setImmediate) { window.setImmediate(expr); } else { window.setTimeout(expr, 0); } + }, + forEach: function (object, callback) { + if (ko.validation.utils.isArray(object)) { + return ko.utils.arrayForEach(object, callback); + } + for (var prop in object) { + if (object.hasOwnProperty(prop)) { + callback(object[prop], prop); + } + } } }; }()); \ No newline at end of file From 32cdaaac1c00f17227d484512881106016efd937 Mon Sep 17 00:00:00 2001 From: Sergiy Stotskiy Date: Sat, 26 Oct 2013 19:09:06 +0300 Subject: [PATCH 044/165] It fixes #312 --- Src/bindingHandlers.js | 23 ++++---- Tests/validation-ui-tests.js | 101 +++++++++++++++++++++-------------- 2 files changed, 72 insertions(+), 52 deletions(-) diff --git a/Src/bindingHandlers.js b/Src/bindingHandlers.js index 6fef550d..6909d9b8 100644 --- a/Src/bindingHandlers.js +++ b/Src/bindingHandlers.js @@ -117,20 +117,17 @@ ko.bindingHandlers['validationElement'] = { ko.bindingHandlers.css.update(element, cssSettingsAccessor); if (!config.errorsAsTitle) { return; } - var origTitle = ko.validation.utils.getAttribute(element, 'data-orig-title'), - elementTitle = element.title, - titleIsErrorMsg = ko.validation.utils.getAttribute(element, 'data-orig-title') === "true"; - - var errorMsgTitleAccessor = function () { - if (!config.errorsAsTitleOnModified || isModified) { - if (!isValid) { - return { title: obsv.error, 'data-orig-title': ko.validation.utils.getOriginalElementTitle(element) }; - } else { - return { title: ko.validation.utils.getOriginalElementTitle(element), 'data-orig-title': null }; - } + ko.bindingHandlers.attr.update(element, function () { + var + hasModification = !config.errorsAsTitleOnModified || isModified, + title = ko.validation.utils.getOriginalElementTitle(element); + + if (hasModification && !isValid) { + return { title: obsv.error, 'data-orig-title': title }; + } else if (!hasModification || isValid) { + return { title: title, 'data-orig-title': null }; } - }; - ko.bindingHandlers.attr.update(element, errorMsgTitleAccessor); + }); } }; diff --git a/Tests/validation-ui-tests.js b/Tests/validation-ui-tests.js index c7efb22a..d1872964 100644 --- a/Tests/validation-ui-tests.js +++ b/Tests/validation-ui-tests.js @@ -1,9 +1,9 @@ -/*global - module:false, - equal:false, +/*global + module:false, + equal:false, notEqual:false, strictEqual:false, - test:false, + test:false, ok:false, asyncTest:false, start: false, @@ -33,7 +33,7 @@ var addTestHtml = function(html){ }; test('hasAttribute works in old IE', function () { - + addTestHtml(''); var el = document.getElementById('myTestInput'); @@ -56,7 +56,7 @@ test("checked binding sets error class on radio buttons", function() { ko.validation.init({ decorateElement: true }, true); vm.result.isModified(true); //fake a modification - + applyTestBindings(vm); ok(!vm.result.isValid(), "Should initially be invalid"); @@ -84,10 +84,10 @@ test('Inserting Messages Works', function () { var $testInput = $('#myTestInput'); - $testInput.val("a"); //set it + $testInput.val("a"); //set it $testInput.change(); //trigger change event - $testInput.val(""); //set it + $testInput.val(""); //set it $testInput.change(); //trigger change event var isValid = vm.firstName.isValid(); @@ -110,7 +110,7 @@ test('Decorating Elements Works', function () { var vm = { firstName: ko.observable('').extend({ required: true }) }; - + // make sure the options are ok. ko.validation.init({ decorateElement: true @@ -119,15 +119,15 @@ test('Decorating Elements Works', function () { applyTestBindings(vm); var $testInput = $('#myTestInput'); - + ok(!$testInput.hasClass('validationElement'), "CSS class shouldn't present"); - $testInput.val("a"); //set it + $testInput.val("a"); //set it $testInput.change(); //trigger change event - $testInput.val(""); //set it + $testInput.val(""); //set it $testInput.change(); //trigger change event - + ok($testInput.hasClass('validationElement'), "CSS class should present"); }); @@ -138,7 +138,7 @@ test('Decorating Elements On Modified Works', function () { var vm = { firstName: ko.observable('').extend({ required: true }) }; - + // make sure the options are ok. ko.validation.init({ decorateElement: true, @@ -148,12 +148,12 @@ test('Decorating Elements On Modified Works', function () { applyTestBindings(vm); var $testInput = $('#myTestInput'); - + ok($testInput.hasClass('validationElement'), "CSS class should present"); - $testInput.val("a"); //set it + $testInput.val("a"); //set it $testInput.change(); //trigger change event - + ok(!$testInput.hasClass('validationElement'), "CSS class shouldn't present"); }); @@ -179,10 +179,10 @@ test('Showing Errors As Titles Works', function () { var $testInput = $('#myTestInput'); - $testInput.val("a"); //set it + $testInput.val("a"); //set it $testInput.change(); //trigger change event - $testInput.val(""); //set it + $testInput.val(""); //set it $testInput.change(); //trigger change event var isValid = vm.firstName.isValid(); @@ -212,16 +212,16 @@ test('Original titles are restored', function () { var $testInput = $('#myTestInput'); - $testInput.val("a"); //set it + $testInput.val("a"); //set it $testInput.change(); //trigger change event - $testInput.val(""); //set it + $testInput.val(""); //set it $testInput.change(); //trigger change event var msg = $testInput.attr('title'); equal(msg, 'This field is required.', msg); - $testInput.val("a"); //set it + $testInput.val("a"); //set it $testInput.change(); //trigger change event msg = $testInput.attr('title'); @@ -246,10 +246,10 @@ test("Original titles are restored to blank", function () { var $testInput = $('#myTestInput'); - $testInput.val("a"); //set it + $testInput.val("a"); //set it $testInput.change(); //trigger change event - $testInput.val(""); //set it + $testInput.val(""); //set it $testInput.change(); //trigger change event ok(!vm.firstName.isValid(), 'First Name is NOT Valid'); @@ -281,22 +281,22 @@ test('Original titles are restored with multiple validators, too', function () { var $testInput = $('#myTestInput'); - $testInput.val("aa"); //set it + $testInput.val("aa"); //set it $testInput.change(); //trigger change event - $testInput.val(""); //set it + $testInput.val(""); //set it $testInput.change(); //trigger change event var msg = $testInput.attr('title'); equal(msg, 'This field is required.', msg); - $testInput.val("a"); //set it + $testInput.val("a"); //set it $testInput.change(); //trigger change event msg = $testInput.attr('title'); equal(msg, 'Please enter at least 2 characters.', msg); - $testInput.val("aa"); //set it + $testInput.val("aa"); //set it $testInput.change(); //trigger change event msg = $testInput.attr('title'); @@ -323,10 +323,10 @@ test('Showing Errors As Titles is disabled sucessfully', function () { var $testInput = $('#myTestInput'); - $testInput.val("a"); //set it + $testInput.val("a"); //set it $testInput.change(); //trigger change event - $testInput.val(""); //set it + $testInput.val(""); //set it $testInput.change(); //trigger change event var isValid = vm.firstName.isValid(); @@ -338,6 +338,29 @@ test('Showing Errors As Titles is disabled sucessfully', function () { notEqual(msg, 'This field is required.', msg); }); +test("Removing error message from title when isModified is reset", function () { + + addTestHtml(''); + + var vm = { + prop: ko.observable('').extend({ required: true }) + }; + + // make sure the options are ok. + ko.validation.init({ + errorsAsTitleOnModified: true, + decorateInputElement: true, + errorsAsTitle: false + }, true); + + applyTestBindings(vm); + + vm.prop("valid").prop(""); + vm.prop.isModified(false); + + ok(!$("#myTestInput").attr("title")); +}); + //#endregion //#region Validation Option Tests @@ -356,10 +379,10 @@ test('Validation Options - Basic Tests', function () { var $testInput = $('#myTestInput'); - $testInput.val("a"); //set it + $testInput.val("a"); //set it $testInput.change(); //trigger change event - $testInput.val(""); //set it + $testInput.val(""); //set it $testInput.change(); //trigger change event var isValid = vm.firstName.isValid(); @@ -394,7 +417,7 @@ test('Validation Options - Nested Test', function () { var $testInput = $('#myLastName'); - $testInput.val("a"); //set it + $testInput.val("a"); //set it $testInput.change(); //trigger change event var isValid = vm.someObj.lastName.isValid(); @@ -431,7 +454,7 @@ test('Validation Options - Options only apply to their HTML Contexts', function var $testInput = $('#myLastName'); - $testInput.val("a"); //set it + $testInput.val("a"); //set it $testInput.change(); //trigger change event var isValid = vm.someObj.lastName.isValid(); @@ -443,7 +466,7 @@ test('Validation Options - Options only apply to their HTML Contexts', function equal(noMsgs, 0, 'No Messages were inserted'); var $firstName = $('#myFirstName'); - $firstName.val(""); //set it + $firstName.val(""); //set it $firstName.change(); //trigger change event ok(!vm.firstName.isValid(), 'Validation Still works correctly'); @@ -580,7 +603,7 @@ test("Issue #80 - HTML5 attributes - pattern", function () { var $el = $('#testElement'); var el = $el.get(0); - + var param = $el.attr('pattern'); // fire the validity check event @@ -632,11 +655,11 @@ test("HTML5 Input types", function () { runAssertions(); } }, 1); - + function runAssertions() { clearInterval(intervalId); - + var $emailInput = $('#emailInput'); var emailInput = $emailInput.get(0); var $dateInput = $('#dateInput'); @@ -649,7 +672,7 @@ test("HTML5 Input types", function () { ok(!vm.invalidNumber.isValid(), 'Expected date to be considered as invalid.'); start(); - } + } }); From 665fd5f80e26c8aec02a8ed3543a64bb722bd49e Mon Sep 17 00:00:00 2001 From: Tim Larson Date: Wed, 30 Oct 2013 01:26:15 -0400 Subject: [PATCH 045/165] Min and max validation now use type attribute to determine behavior --- README.md | 33 ++- Src/api.js | 20 +- Src/rules.js | 104 ++++++- Tests/validation-ui-tests.js | 531 +++++++++++++++++++++++++++++++++++ 4 files changed, 675 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index ae39d0df..02d12a48 100644 --- a/README.md +++ b/README.md @@ -115,16 +115,39 @@ Learn more about Custom Rules on the [WIKI](https://github.com/Knockout-Contrib/ ##HTML5 Validation Attributes -Required: `` +**Required**: -Min: `` +```html + +``` + +**Min**: -Max: `` +```html + + + +``` -Pattern: `` +**Max**: -Step: `` +```html + + + +``` +**Pattern**: + +```html + +``` + +**Step**: + +```html + +``` **Special Note, the 'MinLength' attribute was removed until the HTML5 spec fully supports it** ##Knockout Bindings diff --git a/Src/api.js b/Src/api.js index 8aa730ed..9a0ee518 100644 --- a/Src/api.js +++ b/Src/api.js @@ -280,9 +280,27 @@ parseInputValidationAttributes: function (element, valueAccessor) { ko.utils.arrayForEach(ko.validation.configuration.html5Attributes, function (attr) { if (utils.hasAttribute(element, attr)) { + + var params = element.getAttribute(attr) || true; + + if (attr === 'min' || attr === 'max') + { + // If we're validating based on the min and max attributes, we'll + // need to know what the 'type' attribute is set to + var typeAttr = element.getAttribute('type'); + if (typeof typeAttr === "undefined" || !typeAttr) + { + // From http://www.w3.org/TR/html-markup/input: + // An input element with no type attribute specified represents the + // same thing as an input element with its type attribute set to "text". + typeAttr = "text"; + } + params = {typeAttr: typeAttr, value: params}; + } + ko.validation.addRule(valueAccessor(), { rule: attr, - params: element.getAttribute(attr) || true + params: params }); } }); diff --git a/Src/rules.js b/Src/rules.js index c8a3994d..92d81dc0 100644 --- a/Src/rules.js +++ b/Src/rules.js @@ -43,20 +43,110 @@ ko.validation.rules['required'] = { message: 'This field is required.' }; +function minMaxValidatorFactory(validatorName) { + var isMaxValidation = validatorName === "max"; + + return function (val, options) { + if (ko.validation.utils.isEmptyVal(val)) { + return true; + } + + var comparisonValue, type; + if (options.typeAttr === undefined) { + // This validator is being called from javascript rather than + // being bound from markup + type = "text"; + comparisonValue = options; + } else { + type = options.typeAttr; + comparisonValue = options.value; + } + + // From http://www.w3.org/TR/2012/WD-html5-20121025/common-input-element-attributes.html#attr-input-min, + // if the value is parseable to a number, then the minimum should be numeric + if (!isNaN(comparisonValue)) { + type = "number"; + } + + var regex, valMatches, comparisonValueMatches; + switch (type.toLowerCase()) { + case "week": + regex = /^(\d{4})-W(\d{2})$/; + valMatches = val.match(regex); + if (valMatches === null) { + throw "Invalid value for " + validatorName + " attribute for week input. Should look like " + + "'2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min"; + } + comparisonValueMatches = comparisonValue.match(regex); + // If no regex matches were found, validation fails + if (!comparisonValueMatches) { + return false; + } + + if (isMaxValidation) { + return (valMatches[1] < comparisonValueMatches[1]) || // older year + // same year, older week + ((valMatches[1] === comparisonValueMatches[1]) && (valMatches[2] <= comparisonValueMatches[2])); + } else { + return (valMatches[1] > comparisonValueMatches[1]) || // newer year + // same year, newer week + ((valMatches[1] === comparisonValueMatches[1]) && (valMatches[2] >= comparisonValueMatches[2])); + } + break; + + case "month": + regex = /^(\d{4})-(\d{2})$/; + valMatches = val.match(regex); + if (valMatches === null) { + throw "Invalid value for " + validatorName + " attribute for month input. Should look like " + + "'2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min"; + } + comparisonValueMatches = comparisonValue.match(regex); + // If no regex matches were found, validation fails + if (!comparisonValueMatches) { + return false; + } + + if (isMaxValidation) { + return ((valMatches[1] < comparisonValueMatches[1]) || // older year + // same year, older month + ((valMatches[1] === comparisonValueMatches[1]) && (valMatches[2] <= comparisonValueMatches[2]))); + } else { + return (valMatches[1] > comparisonValueMatches[1]) || // newer year + // same year, newer month + ((valMatches[1] === comparisonValueMatches[1]) && (valMatches[2] >= comparisonValueMatches[2])); + } + break; + + case "number": + case "range": + if (isMaxValidation) { + return (!isNaN(val) && parseFloat(val) <= parseFloat(comparisonValue)); + } else { + return (!isNaN(val) && parseFloat(val) >= parseFloat(comparisonValue)); + } + break; + + default: + if (isMaxValidation) { + return val <= comparisonValue; + } else { + return val >= comparisonValue; + } + } + }; +} + ko.validation.rules['min'] = { - validator: function (val, min) { - return ko.validation.utils.isEmptyVal(val) || val >= min; - }, + validator: minMaxValidatorFactory("min"), message: 'Please enter a value greater than or equal to {0}.' }; ko.validation.rules['max'] = { - validator: function (val, max) { - return ko.validation.utils.isEmptyVal(val) || val <= max; - }, + validator: minMaxValidatorFactory("max"), message: 'Please enter a value less than or equal to {0}.' }; - + ko.validation.rules['minLength'] = { validator: function (val, minLength) { return ko.validation.utils.isEmptyVal(val) || val.length >= minLength; diff --git a/Tests/validation-ui-tests.js b/Tests/validation-ui-tests.js index d1872964..d0f45a1c 100644 --- a/Tests/validation-ui-tests.js +++ b/Tests/validation-ui-tests.js @@ -615,6 +615,17 @@ test("Issue #80 - HTML5 attributes - pattern", function () { strictEqual(vm.testObj(), 'something', 'Observable still works'); }); +module('HTML5 UI Tests', { + setup: function () { + + }, + teardown: function () { + ko.cleanNode($('#testContainer')[0]); + $('#testContainer').empty(); + ko.validation.reset(); + } +}); + test("HTML5 Input types", function () { var vm = { @@ -675,6 +686,526 @@ test("HTML5 Input types", function () { } }); +test('min Attribute of 20 should fail for value of 8', function () { + + var vm = { + someNumber: ko.validatedObservable() + }; + + addTestHtml(''); + + ko.validation.init({ + parseInputAttributes: true + }, true); + applyTestBindings(vm); + stop(); + + setTimeout(function() { + vm.someNumber(8); // should fail the max rule + + var el = $('#myTestInput'); + + ok(el, 'found element'); + ok(!vm.someNumber.isValid(), "Object is not valid"); + + start(); + }, 1); +}); + +test('min Attribute of 20 should fail for value of "8"', function () { + + var vm = { + someNumber: ko.validatedObservable() + }; + + addTestHtml(''); + ko.validation.init({ + parseInputAttributes: true + }, true); + applyTestBindings(vm); + stop(); + + setTimeout(function() { + vm.someNumber("8"); // should fail the min rule + + var el = $('#myTestInput'); + + ok(el, 'found element'); + ok(!vm.someNumber.isValid(), "Object is not valid"); + + start(); + }, 1); +}); + +test('min Attribute of 20 should fail for value of "8" with text type', function () { + + var vm = { + someNumber: ko.validatedObservable() + }; + + addTestHtml(''); + + ko.validation.init({ + parseInputAttributes: true + }, true); + applyTestBindings(vm); + stop(); + + setTimeout(function() { + vm.someNumber("8"); // should fail the min rule + + var el = $('#myTestInput'); + + ok(el, 'found element'); + ok(!vm.someNumber.isValid(), "Object is not valid"); + + start(); + }, 1); +}); + +test('min Attribute of 20 should pass for value of 110', function () { + + var vm = { + someNumber: ko.validatedObservable() + }; + + addTestHtml(''); + + ko.validation.init({ + parseInputAttributes: true, + }, true); + applyTestBindings(vm); + stop(); + + setTimeout(function() { + vm.someNumber(110); // should validate the min rule + + var el = $('#myTestInput'); + + ok(el, 'found element'); + ok(vm.someNumber.isValid(), "Object is valid"); + + start(); + }, 1); + +}); + +test('MIN Attribute of 20 should pass for value of "110"', function () { + + var vm = { + someNumber: ko.validatedObservable() + }; + + addTestHtml(''); + + ko.validation.init({ + parseInputAttributes: true, + }, true); + applyTestBindings(vm); + stop(); + + setTimeout(function() { + vm.someNumber("110"); // should validate the min rule + + var el = $('#myTestInput'); + + ok(el, 'found element'); + ok(vm.someNumber.isValid(), "Object is valid"); + + start(); + }, 1); + +}); + +test('max Attribute of 30 should fail for value of 100', function () { + + var vm = { + someNumber: ko.validatedObservable() + }; + + addTestHtml(''); + + ko.validation.init({ + parseInputAttributes: true + }, true); + applyTestBindings(vm); + stop(); + + setTimeout(function() { + vm.someNumber(100); // should fail the max rule + + var el = $('#myTestInput'); + + ok(el, 'found element'); + ok(!vm.someNumber.isValid(), "Object is not valid"); + + start(); + }, 1); +}); + +test('max Attribute of 30 should fail for value of "100"', function () { + + var vm = { + someNumber: ko.validatedObservable() + }; + + addTestHtml(''); + ko.validation.init({ + parseInputAttributes: true + }, true); + applyTestBindings(vm); + stop(); + + setTimeout(function() { + vm.someNumber("100"); // should fail the min rule + + var el = $('#myTestInput'); + + ok(el, 'found element'); + ok(!vm.someNumber.isValid(), "Object is not valid"); + + start(); + }, 1); +}); + +test('max Attribute of 30 should fail for value of "100" with text type', function () { + + var vm = { + someNumber: ko.validatedObservable() + }; + + addTestHtml(''); + + ko.validation.init({ + parseInputAttributes: true + }, true); + applyTestBindings(vm); + stop(); + + setTimeout(function() { + vm.someNumber(100); // should fail the min rule + + var el = $('#myTestInput'); + + ok(el, 'found element'); + ok(!vm.someNumber.isValid(), "Object is not valid"); + + start(); + }, 1); +}); + +test('max Attribute of 30 should pass for value of 5', function () { + + var vm = { + someNumber: ko.validatedObservable() + }; + + addTestHtml(''); + + ko.validation.init({ + parseInputAttributes: true, + }, true); + applyTestBindings(vm); + stop(); + + setTimeout(function() { + vm.someNumber(5); // should validate the min rule + + var el = $('#myTestInput'); + + ok(el, 'found element'); + ok(vm.someNumber.isValid(), "Object is valid"); + + start(); + }, 1); + +}); + +test('max Attribute of 30 should pass for value of "5"', function () { + + var vm = { + someNumber: ko.validatedObservable() + }; + + addTestHtml(''); + + ko.validation.init({ + parseInputAttributes: true, + }, true); + applyTestBindings(vm); + stop(); + + setTimeout(function() { + vm.someNumber("5"); // should validate the min rule + + var el = $('#myTestInput'); + + ok(el, 'found element'); + ok(vm.someNumber.isValid(), "Object is valid"); + + start(); + }, 1); + +}); + +test('max Attribute of 2010-09 should fail for value of 2011-03', function () { + + var vm = { + someNumber: ko.validatedObservable() + }; + + addTestHtml(''); + + ko.validation.init({ + parseInputAttributes: true + }, true); + applyTestBindings(vm); + stop(); + + setTimeout(function() { + vm.someNumber("2011-03"); // should fail the max rule + + var el = $('#myTestInput'); + + ok(el, 'found element'); + ok(!vm.someNumber.isValid(), "Object is not valid"); + + start(); + }, 1); +}); + +test('max Attribute of 2010-09 should succeed for value of 2010-08', function () { + + var vm = { + someNumber: ko.validatedObservable() + }; + + addTestHtml(''); + + ko.validation.init({ + parseInputAttributes: true + }, true); + applyTestBindings(vm); + stop(); + + setTimeout(function() { + vm.someNumber("2010-08"); // should succeed the max rule + + var el = $('#myTestInput'); + + ok(el, 'found element'); + ok(vm.someNumber.isValid(), "Object is valid"); + + start(); + }, 1); +}); + +test('min Attribute of 2010-09 should fail for value of 2010-08', function () { + + var vm = { + someNumber: ko.validatedObservable() + }; + + addTestHtml(''); + + ko.validation.init({ + parseInputAttributes: true + }, true); + applyTestBindings(vm); + stop(); + + setTimeout(function() { + vm.someNumber("2010-08"); // should fail the min rule + + var el = $('#myTestInput'); + + ok(el, 'found element'); + ok(!vm.someNumber.isValid(), "Object is valid"); + + start(); + }, 1); +}); + +test('min Attribute of 2012-05 should fail for value of 2011-01', function () { + + var vm = { + someNumber: ko.validatedObservable() + }; + + addTestHtml(''); + + ko.validation.init({ + parseInputAttributes: true + }, true); + applyTestBindings(vm); + stop(); + + setTimeout(function() { + vm.someNumber("2011-01"); // should fail the min rule + + var el = $('#myTestInput'); + + ok(el, 'found element'); + ok(!vm.someNumber.isValid(), "Object is valid"); + + start(); + }, 1); +}); + +test('min Attribute of 2012-03 should succeed for value of 2013-01', function () { + + var vm = { + someNumber: ko.validatedObservable() + }; + + addTestHtml(''); + + ko.validation.init({ + parseInputAttributes: true + }, true); + applyTestBindings(vm); + stop(); + + setTimeout(function() { + vm.someNumber("2013-01"); // should succeed the min rule + + var el = $('#myTestInput'); + + ok(el, 'found element'); + ok(vm.someNumber.isValid(), "Object is valid"); + + start(); + }, 1); +}); + +test('max Attribute of 2010-W09 should fail for value of 2011-W03', function () { + var vm = { + someNumber: ko.validatedObservable() + }; + + addTestHtml(''); + + ko.validation.init({ + parseInputAttributes: true + }, true); + applyTestBindings(vm); + stop(); + + setTimeout(function() { + vm.someNumber("2011-W03"); // should fail the max rule + + var el = $('#myTestInput'); + + ok(el, 'found element'); + ok(!vm.someNumber.isValid(), "Object is not valid"); + + start(); + }, 1); +}); + +test('max Attribute of 2010-W09 should succeed for value of 2010-W08', function () { + + var vm = { + someNumber: ko.validatedObservable() + }; + + addTestHtml(''); + + ko.validation.init({ + parseInputAttributes: true + }, true); + applyTestBindings(vm); + stop(); + + setTimeout(function() { + vm.someNumber("2010-W08"); // should succeed the max rule + + var el = $('#myTestInput'); + + ok(el, 'found element'); + ok(vm.someNumber.isValid(), "Object is valid"); + + start(); + }, 1); +}); + +test('min Attribute of 2010-W09 should fail for value of 2010-W08', function () { + + var vm = { + someNumber: ko.validatedObservable() + }; + + addTestHtml(''); + + ko.validation.init({ + parseInputAttributes: true + }, true); + applyTestBindings(vm); + stop(); + + setTimeout(function() { + vm.someNumber("2010-W08"); // should fail the min rule + + var el = $('#myTestInput'); + + ok(el, 'found element'); + ok(!vm.someNumber.isValid(), "Object is valid"); + + start(); + }, 1); +}); + +test('min Attribute of 2012-W05 should fail for value of 2011-W01', function () { + + var vm = { + someNumber: ko.validatedObservable() + }; + + addTestHtml(''); + + ko.validation.init({ + parseInputAttributes: true + }, true); + applyTestBindings(vm); + stop(); + + setTimeout(function() { + vm.someNumber("2011-W01"); // should fail the min rule + + var el = $('#myTestInput'); + + ok(el, 'found element'); + ok(!vm.someNumber.isValid(), "Object is valid"); + + start(); + }, 1); +}); + +test('min Attribute of 2012-W03 should succeed for value of 2013-W01', function () { + + var vm = { + someNumber: ko.validatedObservable() + }; + + addTestHtml(''); + + ko.validation.init({ + parseInputAttributes: true + }, true); + applyTestBindings(vm); + stop(); + + setTimeout(function() { + vm.someNumber("2013-W01"); // should succeed the min rule + + var el = $('#myTestInput'); + + ok(el, 'found element'); + ok(vm.someNumber.isValid(), "Object is valid"); + + start(); + }, 1); +}); //#endregion \ No newline at end of file From aeaf708f1bf80c06f264f8bdafaa4dc63506ca54 Mon Sep 17 00:00:00 2001 From: Steve Greatrex Date: Mon, 4 Nov 2013 17:15:07 +0000 Subject: [PATCH 046/165] Updated to ko 3.0 and updated package.json for npm publishing --- .gitignore | 3 +- Dist/knockout.validation.js | 451 +- Dist/knockout.validation.min.js | 2 +- Lib/knockout-latest.debug.js | 7894 +++++++++++++++++-------------- Localization/ko-KR.js | 78 +- package.json | 3 +- 6 files changed, 4553 insertions(+), 3878 deletions(-) diff --git a/.gitignore b/.gitignore index 21f654f8..d3bcf7c8 100644 --- a/.gitignore +++ b/.gitignore @@ -18,4 +18,5 @@ target *.ncrunchsolution node_modules -*.webinfo \ No newline at end of file +*.webinfo +*.log \ No newline at end of file diff --git a/Dist/knockout.validation.js b/Dist/knockout.validation.js index b45fdb8f..93916929 100644 --- a/Dist/knockout.validation.js +++ b/Dist/knockout.validation.js @@ -25,7 +25,14 @@ if (typeof (ko) === undefined) { throw 'Knockout is required, please ensure it is loaded before loading this validation plug-in'; } // create our namespace object - ko.validation = exports;;/*global ko: false*/ + ko.validation = exports; + + var kv = ko.validation; + var koUtils = ko.utils; + var unwrap = koUtils.unwrapObservable; + var forEach = koUtils.arrayForEach; + var extend = koUtils.extend; +;/*global ko: false*/ var defaults = { registerExtenders: true, @@ -44,20 +51,24 @@ var defaults = { grouping: { deep: false, //by default grouping is shallow observable: true //and using observables + }, + validate: { + // throttle: 10 } }; // make a copy so we can use 'reset' later -var configuration = ko.utils.extend({}, defaults); +var configuration = extend({}, defaults); configuration.html5Attributes = ['required', 'pattern', 'min', 'max', 'step']; configuration.html5InputTypes = ['email', 'number', 'date']; configuration.reset = function () { - ko.utils.extend(configuration, defaults); + extend(configuration, defaults); }; -ko.validation.configuration = configuration;;ko.validation.utils = (function () { +kv.configuration = configuration; +;kv.utils = (function () { var seedId = new Date().getTime(); var domData = {}; //hash of data objects that we reference from dom elements @@ -101,15 +112,15 @@ ko.validation.configuration = configuration;;ko.validation.utils = (function () return seedId += 1; }, getConfigOptions: function (element) { - var options = ko.validation.utils.contextFor(element); + var options = kv.utils.contextFor(element); - return options || ko.validation.configuration; + return options || kv.configuration; }, setDomData: function (node, data) { var key = node[domDataKey]; if (!key) { - node[domDataKey] = key = ko.validation.utils.newId(); + node[domDataKey] = key = kv.utils.newId(); } domData[key] = data; @@ -127,9 +138,9 @@ ko.validation.configuration = configuration;;ko.validation.utils = (function () switch (node.nodeType) { case 1: case 8: - var context = ko.validation.utils.getDomData(node); + var context = kv.utils.getDomData(node); if (context) { return context; } - if (node.parentNode) { return ko.validation.utils.contextFor(node.parentNode); } + if (node.parentNode) { return kv.utils.contextFor(node.parentNode); } break; } return undefined; @@ -146,9 +157,9 @@ ko.validation.configuration = configuration;;ko.validation.utils = (function () } }, getOriginalElementTitle: function (element) { - var savedOriginalTitle = ko.validation.utils.getAttribute(element, 'data-orig-title'), + var savedOriginalTitle = kv.utils.getAttribute(element, 'data-orig-title'), currentTitle = element.title, - hasSavedOriginalTitle = ko.validation.utils.hasAttribute(element, 'data-orig-title'); + hasSavedOriginalTitle = kv.utils.hasAttribute(element, 'data-orig-title'); return hasSavedOriginalTitle ? savedOriginalTitle : currentTitle; @@ -161,8 +172,8 @@ ko.validation.configuration = configuration;;ko.validation.utils = (function () }());;var api = (function () { var isInitialized = 0, - configuration = ko.validation.configuration, - utils = ko.validation.utils; + configuration = kv.configuration, + utils = kv.utils; return { //Call this on startup @@ -181,19 +192,19 @@ ko.validation.configuration = configuration;;ko.validation.utils = (function () options.errorElementClass = options.errorElementClass || options.errorClass || configuration.errorElementClass; options.errorMessageClass = options.errorMessageClass || options.errorClass || configuration.errorMessageClass; - ko.utils.extend(configuration, options); + extend(configuration, options); if (configuration.registerExtenders) { - ko.validation.registerExtenders(); + kv.registerExtenders(); } isInitialized = 1; }, // backwards compatability - configure: function (options) { ko.validation.init(options); }, + configure: function (options) { kv.init(options); }, // resets the config back to its original state - reset: ko.validation.configuration.reset, + reset: kv.configuration.reset, // recursivly walks a viewModel and creates an object that // provides validation information for the entire viewModel @@ -203,7 +214,7 @@ ko.validation.configuration = configuration;;ko.validation.utils = (function () // observable: false // if true, returns a computed observable indicating if the viewModel is valid // } group: function group(obj, options) { // array of observables or viewModel - options = ko.utils.extend(ko.utils.extend({}, configuration.grouping), options); + options = extend(extend({}, configuration.grouping), options); var validatables = ko.observableArray([]), result = null, @@ -211,7 +222,7 @@ ko.validation.configuration = configuration;;ko.validation.utils = (function () dispose = function () { if (options.deep) { - ko.utils.arrayForEach(flagged, function (obj) { + forEach(flagged, function (obj) { delete obj.__kv_traversed; }); } @@ -221,7 +232,7 @@ ko.validation.configuration = configuration;;ko.validation.utils = (function () //if !options.deep then it will stop on top level traverse = function traverse(obj, level) { var objValues = [], - val = ko.utils.unwrapObservable(obj); + val = unwrap(obj); if (obj.__kv_traversed === true) { return; } @@ -252,7 +263,7 @@ ko.validation.configuration = configuration;;ko.validation.utils = (function () //process recurisvely if it is deep grouping if (level !== 0) { - ko.utils.arrayForEach(objValues, function (observable) { + forEach(objValues, function (observable) { //but not falsy things and not HTML Elements if (observable && !observable.nodeType) { traverse(observable, level + 1); } @@ -268,7 +279,7 @@ ko.validation.configuration = configuration;;ko.validation.utils = (function () result = ko.computed(function () { var errors = []; - ko.utils.arrayForEach(validatables(), function (observable) { + forEach(validatables(), function (observable) { if (!observable.isValid()) { errors.push(observable.error); } @@ -283,7 +294,7 @@ ko.validation.configuration = configuration;;ko.validation.utils = (function () traverse(obj); // and traverse tree again dispose(); - ko.utils.arrayForEach(validatables(), function (observable) { + forEach(validatables(), function (observable) { if (!observable.isValid()) { errors.push(observable.error); } @@ -300,7 +311,7 @@ ko.validation.configuration = configuration;;ko.validation.utils = (function () // ensure we have latest changes result(); - ko.utils.arrayForEach(validatables(), function (observable) { + forEach(validatables(), function (observable) { observable.isModified(show); }); }; @@ -315,7 +326,7 @@ ko.validation.configuration = configuration;;ko.validation.utils = (function () // ensure we have latest changes result(); - ko.utils.arrayForEach(validatables(), function (observable) { + forEach(validatables(), function (observable) { if (!observable.isValid() && observable.isModified()) { invalidAndModifiedPresent = true; } @@ -330,12 +341,12 @@ ko.validation.configuration = configuration;;ko.validation.utils = (function () if (typeof (message) === 'function') { return message(params); } - return message.replace(/\{0\}/gi, ko.utils.unwrapObservable(params)); + return message.replace(/\{0\}/gi, unwrap(params)); }, // addRule: // This takes in a ko.observable and a Rule Context - which is just a rule name and params to supply to the validator - // ie: ko.validation.addRule(myObservable, { + // ie: kv.addRule(myObservable, { // rule: 'required', // params: true // }); @@ -350,7 +361,7 @@ ko.validation.configuration = configuration;;ko.validation.utils = (function () // addAnonymousRule: // Anonymous Rules essentially have all the properties of a Rule, but are only specific for a certain property - // and developers typically are wanting to add them on the fly or not register a rule with the 'ko.validation.rules' object + // and developers typically are wanting to add them on the fly or not register a rule with the 'kv.rules' object // // Example: // var test = ko.observable('something').extend{( @@ -370,10 +381,10 @@ ko.validation.configuration = configuration;;ko.validation.utils = (function () } //Create an anonymous rule to reference - ko.validation.rules[ruleName] = ruleObj; + kv.rules[ruleName] = ruleObj; //add the anonymous rule to the observable - ko.validation.addRule(observable, { + kv.addRule(observable, { rule: ruleName, params: ruleObj.params }); @@ -398,14 +409,14 @@ ko.validation.configuration = configuration;;ko.validation.utils = (function () // )}; // if (params.message || params.onlyIf) { //if it has a message or condition object, then its an object literal to use - return ko.validation.addRule(observable, { + return kv.addRule(observable, { rule: ruleName, message: params.message, params: utils.isEmptyVal(params.params) ? true : params.params, condition: params.onlyIf }); } else { - return ko.validation.addRule(observable, { + return kv.addRule(observable, { rule: ruleName, params: params }); @@ -413,14 +424,14 @@ ko.validation.configuration = configuration;;ko.validation.utils = (function () }; }, - // loops through all ko.validation.rules and adds them as extenders to + // loops through all kv.rules and adds them as extenders to // ko.extenders registerExtenders: function () { // root extenders optional, use 'validation' extender if would cause conflicts if (configuration.registerExtenders) { - for (var ruleName in ko.validation.rules) { - if (ko.validation.rules.hasOwnProperty(ruleName)) { + for (var ruleName in kv.rules) { + if (kv.rules.hasOwnProperty(ruleName)) { if (!ko.extenders[ruleName]) { - ko.validation.addExtender(ruleName); + kv.addExtender(ruleName); } } } @@ -438,19 +449,37 @@ ko.validation.configuration = configuration;;ko.validation.utils = (function () // if html-5 validation attributes have been specified, this parses // the attributes on @element parseInputValidationAttributes: function (element, valueAccessor) { - ko.utils.arrayForEach(ko.validation.configuration.html5Attributes, function (attr) { + forEach(kv.configuration.html5Attributes, function (attr) { if (utils.hasAttribute(element, attr)) { - ko.validation.addRule(valueAccessor(), { + + var params = element.getAttribute(attr) || true; + + if (attr === 'min' || attr === 'max') + { + // If we're validating based on the min and max attributes, we'll + // need to know what the 'type' attribute is set to + var typeAttr = element.getAttribute('type'); + if (typeof typeAttr === "undefined" || !typeAttr) + { + // From http://www.w3.org/TR/html-markup/input: + // An input element with no type attribute specified represents the + // same thing as an input element with its type attribute set to "text". + typeAttr = "text"; + } + params = {typeAttr: typeAttr, value: params}; + } + + kv.addRule(valueAccessor(), { rule: attr, - params: element.getAttribute(attr) || true + params: params }); } }); var currentType = element.getAttribute('type'); - ko.utils.arrayForEach(ko.validation.configuration.html5InputTypes, function (type) { + forEach(kv.configuration.html5InputTypes, function (type) { if (type === currentType) { - ko.validation.addRule(valueAccessor(), { + kv.addRule(valueAccessor(), { rule: (type === 'date') ? 'dateISO' : type, params: true }); @@ -469,9 +498,9 @@ ko.validation.configuration = configuration;;ko.validation.utils = (function () var contexts = observable.rules(); // observable array // loop through the attributes and add the information needed - ko.utils.arrayForEach(ko.validation.configuration.html5Attributes, function (attr) { + forEach(kv.configuration.html5Attributes, function (attr) { var params; - var ctx = ko.utils.arrayFirst(contexts, function (ctx) { + var ctx = koUtils.arrayFirst(contexts, function (ctx) { return ctx.rule.toLowerCase() === attr.toLowerCase(); }); @@ -511,12 +540,12 @@ ko.validation.configuration = configuration;;ko.validation.utils = (function () }()); // expose api publicly -ko.utils.extend(ko.validation, api);;//Validation Rules: +extend(ko.validation, api);;//Validation Rules: // You can view and override messages or rules via: -// ko.validation.rules[ruleName] +// kv.rules[ruleName] // // To implement a custom Rule, simply use this template: -// ko.validation.rules[''] = { +// kv.rules[''] = { // validator: function (val, param) { // // return ; @@ -525,15 +554,15 @@ ko.utils.extend(ko.validation, api);;//Validation Rules: // }; // // Example: -// ko.validation.rules['mustEqual'] = { +// kv.rules['mustEqual'] = { // validator: function( val, mustEqualVal ){ // return val === mustEqualVal; // }, // message: 'This field must equal {0}' // }; // -ko.validation.rules = {}; -ko.validation.rules['required'] = { +kv.rules = {}; +kv.rules['required'] = { validator: function (val, required) { var stringTrimRegEx = /^\s+|\s+$/g, testVal; @@ -556,60 +585,150 @@ ko.validation.rules['required'] = { message: 'This field is required.' }; -ko.validation.rules['min'] = { - validator: function (val, min) { - return ko.validation.utils.isEmptyVal(val) || val >= min; - }, +function minMaxValidatorFactory(validatorName) { + var isMaxValidation = validatorName === "max"; + + return function (val, options) { + if (kv.utils.isEmptyVal(val)) { + return true; + } + + var comparisonValue, type; + if (options.typeAttr === undefined) { + // This validator is being called from javascript rather than + // being bound from markup + type = "text"; + comparisonValue = options; + } else { + type = options.typeAttr; + comparisonValue = options.value; + } + + // From http://www.w3.org/TR/2012/WD-html5-20121025/common-input-element-attributes.html#attr-input-min, + // if the value is parseable to a number, then the minimum should be numeric + if (!isNaN(comparisonValue)) { + type = "number"; + } + + var regex, valMatches, comparisonValueMatches; + switch (type.toLowerCase()) { + case "week": + regex = /^(\d{4})-W(\d{2})$/; + valMatches = val.match(regex); + if (valMatches === null) { + throw "Invalid value for " + validatorName + " attribute for week input. Should look like " + + "'2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min"; + } + comparisonValueMatches = comparisonValue.match(regex); + // If no regex matches were found, validation fails + if (!comparisonValueMatches) { + return false; + } + + if (isMaxValidation) { + return (valMatches[1] < comparisonValueMatches[1]) || // older year + // same year, older week + ((valMatches[1] === comparisonValueMatches[1]) && (valMatches[2] <= comparisonValueMatches[2])); + } else { + return (valMatches[1] > comparisonValueMatches[1]) || // newer year + // same year, newer week + ((valMatches[1] === comparisonValueMatches[1]) && (valMatches[2] >= comparisonValueMatches[2])); + } + break; + + case "month": + regex = /^(\d{4})-(\d{2})$/; + valMatches = val.match(regex); + if (valMatches === null) { + throw "Invalid value for " + validatorName + " attribute for month input. Should look like " + + "'2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min"; + } + comparisonValueMatches = comparisonValue.match(regex); + // If no regex matches were found, validation fails + if (!comparisonValueMatches) { + return false; + } + + if (isMaxValidation) { + return ((valMatches[1] < comparisonValueMatches[1]) || // older year + // same year, older month + ((valMatches[1] === comparisonValueMatches[1]) && (valMatches[2] <= comparisonValueMatches[2]))); + } else { + return (valMatches[1] > comparisonValueMatches[1]) || // newer year + // same year, newer month + ((valMatches[1] === comparisonValueMatches[1]) && (valMatches[2] >= comparisonValueMatches[2])); + } + break; + + case "number": + case "range": + if (isMaxValidation) { + return (!isNaN(val) && parseFloat(val) <= parseFloat(comparisonValue)); + } else { + return (!isNaN(val) && parseFloat(val) >= parseFloat(comparisonValue)); + } + break; + + default: + if (isMaxValidation) { + return val <= comparisonValue; + } else { + return val >= comparisonValue; + } + } + }; +} + +kv.rules['min'] = { + validator: minMaxValidatorFactory("min"), message: 'Please enter a value greater than or equal to {0}.' }; -ko.validation.rules['max'] = { - validator: function (val, max) { - return ko.validation.utils.isEmptyVal(val) || val <= max; - }, +kv.rules['max'] = { + validator: minMaxValidatorFactory("max"), message: 'Please enter a value less than or equal to {0}.' }; - -ko.validation.rules['minLength'] = { + +kv.rules['minLength'] = { validator: function (val, minLength) { - return ko.validation.utils.isEmptyVal(val) || val.length >= minLength; + return kv.utils.isEmptyVal(val) || val.length >= minLength; }, message: 'Please enter at least {0} characters.' }; -ko.validation.rules['maxLength'] = { +kv.rules['maxLength'] = { validator: function (val, maxLength) { - return ko.validation.utils.isEmptyVal(val) || val.length <= maxLength; + return kv.utils.isEmptyVal(val) || val.length <= maxLength; }, message: 'Please enter no more than {0} characters.' }; -ko.validation.rules['pattern'] = { +kv.rules['pattern'] = { validator: function (val, regex) { - return ko.validation.utils.isEmptyVal(val) || val.toString().match(regex) !== null; + return kv.utils.isEmptyVal(val) || val.toString().match(regex) !== null; }, message: 'Please check this value.' }; -ko.validation.rules['step'] = { +kv.rules['step'] = { validator: function (val, step) { // 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 (ko.validation.utils.isEmptyVal(val) || step === 'any') { return true; } + 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; }, message: 'The value must increment by {0}' }; -ko.validation.rules['email'] = { +kv.rules['email'] = { validator: function (val, validate) { if (!validate) { return true; } //I think an empty email address is also a valid entry //if one want's to enforce entry it should be done with 'required: true' - return ko.validation.utils.isEmptyVal(val) || ( + return kv.utils.isEmptyVal(val) || ( // jquery validate regex - thanks Scott Gonzalez validate && /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(val) ); @@ -617,42 +736,42 @@ ko.validation.rules['email'] = { message: 'Please enter a proper email address' }; -ko.validation.rules['date'] = { +kv.rules['date'] = { validator: function (value, validate) { if (!validate) { return true; } - return ko.validation.utils.isEmptyVal(value) || (validate && !/Invalid|NaN/.test(new Date(value))); + return kv.utils.isEmptyVal(value) || (validate && !/Invalid|NaN/.test(new Date(value))); }, message: 'Please enter a proper date' }; -ko.validation.rules['dateISO'] = { +kv.rules['dateISO'] = { validator: function (value, validate) { if (!validate) { return true; } - return ko.validation.utils.isEmptyVal(value) || (validate && /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(value)); + return kv.utils.isEmptyVal(value) || (validate && /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(value)); }, message: 'Please enter a proper date' }; -ko.validation.rules['number'] = { +kv.rules['number'] = { validator: function (value, validate) { if (!validate) { return true; } - return ko.validation.utils.isEmptyVal(value) || (validate && /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(value)); + return kv.utils.isEmptyVal(value) || (validate && /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(value)); }, message: 'Please enter a number' }; -ko.validation.rules['digit'] = { +kv.rules['digit'] = { validator: function (value, validate) { if (!validate) { return true; } - return ko.validation.utils.isEmptyVal(value) || (validate && /^\d+$/.test(value)); + return kv.utils.isEmptyVal(value) || (validate && /^\d+$/.test(value)); }, message: 'Please enter a digit' }; -ko.validation.rules['phoneUS'] = { +kv.rules['phoneUS'] = { validator: function (phoneNumber, validate) { if (!validate) { return true; } - if (ko.validation.utils.isEmptyVal(phoneNumber)) { return true; } // makes it optional, use 'required' rule if it should be required + if (kv.utils.isEmptyVal(phoneNumber)) { return true; } // makes it optional, use 'required' rule if it should be required if (typeof (phoneNumber) !== 'string') { return false; } phoneNumber = phoneNumber.replace(/\s+/g, ""); return validate && phoneNumber.length > 9 && phoneNumber.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/); @@ -660,18 +779,18 @@ ko.validation.rules['phoneUS'] = { message: 'Please specify a valid phone number' }; -ko.validation.rules['equal'] = { +kv.rules['equal'] = { validator: function (val, params) { var otherValue = params; - return val === ko.validation.utils.getValue(otherValue); + return val === kv.utils.getValue(otherValue); }, message: 'Values must equal' }; -ko.validation.rules['notEqual'] = { +kv.rules['notEqual'] = { validator: function (val, params) { var otherValue = params; - return val !== ko.validation.utils.getValue(otherValue); + return val !== kv.utils.getValue(otherValue); }, message: 'Please choose another value.' }; @@ -683,15 +802,15 @@ ko.validation.rules['notEqual'] = { // valueAccessor: function that returns value from an object stored in collection // if it is null the value is compared directly // external: set to true when object you are validating is automatically updating collection -ko.validation.rules['unique'] = { +kv.rules['unique'] = { validator: function (val, options) { - var c = ko.validation.utils.getValue(options.collection), - external = ko.validation.utils.getValue(options.externalValue), + var c = kv.utils.getValue(options.collection), + external = kv.utils.getValue(options.externalValue), counter = 0; if (!val || !c) { return true; } - ko.utils.arrayFilter(ko.utils.unwrapObservable(c), function (item) { + koUtils.arrayFilter(unwrap(c), function (item) { if (val === (options.valueAccessor ? options.valueAccessor(item) : item)) { counter++; } }); // if value is external even 1 same value in collection means the value is not unique @@ -703,7 +822,7 @@ ko.validation.rules['unique'] = { //now register all of these! (function () { - ko.validation.registerExtenders(); + kv.registerExtenders(); }()); ;// The core binding handler // this allows us to setup any value binding that internally always @@ -712,36 +831,37 @@ ko.bindingHandlers['validationCore'] = (function () { return { init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { - var config = ko.validation.utils.getConfigOptions(element); + var config = kv.utils.getConfigOptions(element); + var observable = valueAccessor(); // parse html5 input validation attributes, optional feature if (config.parseInputAttributes) { - ko.validation.utils.async(function () { ko.validation.parseInputValidationAttributes(element, valueAccessor); }); + kv.utils.async(function () { kv.parseInputValidationAttributes(element, valueAccessor); }); } // if requested insert message element and apply bindings - if (config.insertMessages && ko.validation.utils.isValidatable(valueAccessor())) { + if (config.insertMessages && kv.utils.isValidatable(observable)) { // insert the - var validationMessageElement = ko.validation.insertValidationMessage(element); + var validationMessageElement = kv.insertValidationMessage(element); // if we're told to use a template, make sure that gets rendered if (config.messageTemplate) { - ko.renderTemplate(config.messageTemplate, { field: valueAccessor() }, null, validationMessageElement, 'replaceNode'); + ko.renderTemplate(config.messageTemplate, { field: observable }, null, validationMessageElement, 'replaceNode'); } else { - ko.applyBindingsToNode(validationMessageElement, { validationMessage: valueAccessor() }); + ko.applyBindingsToNode(validationMessageElement, { validationMessage: observable }); } } // write the html5 attributes if indicated by the config - if (config.writeInputAttributes && ko.validation.utils.isValidatable(valueAccessor())) { + if (config.writeInputAttributes && kv.utils.isValidatable(observable)) { - ko.validation.writeInputValidationAttributes(element, valueAccessor); + kv.writeInputValidationAttributes(element, valueAccessor); } // if requested, add binding to decorate element - if (config.decorateElement && ko.validation.utils.isValidatable(valueAccessor())) { - ko.applyBindingsToNode(element, { validationElement: valueAccessor() }); + if (config.decorateElement && kv.utils.isValidatable(observable)) { + ko.applyBindingsToNode(element, { validationElement: observable }); } }, @@ -753,15 +873,15 @@ ko.bindingHandlers['validationCore'] = (function () { }()); // override for KO's default 'value' and 'checked' bindings -ko.validation.makeBindingHandlerValidatable("value"); -ko.validation.makeBindingHandlerValidatable("checked"); +kv.makeBindingHandlerValidatable("value"); +kv.makeBindingHandlerValidatable("checked"); ko.bindingHandlers['validationMessage'] = { // individual error message, if modified or post binding update: function (element, valueAccessor) { var obsv = valueAccessor(), - config = ko.validation.utils.getConfigOptions(element), - val = ko.utils.unwrapObservable(obsv), + config = kv.utils.getConfigOptions(element), + val = unwrap(obsv), msg = null, isModified = false, isValid = false; @@ -793,8 +913,8 @@ ko.bindingHandlers['validationMessage'] = { // individual error message, if modi ko.bindingHandlers['validationElement'] = { update: function (element, valueAccessor) { var obsv = valueAccessor(), - config = ko.validation.utils.getConfigOptions(element), - val = ko.utils.unwrapObservable(obsv), + config = kv.utils.getConfigOptions(element), + val = unwrap(obsv), msg = null, isModified = false, isValid = false; @@ -823,20 +943,17 @@ ko.bindingHandlers['validationElement'] = { ko.bindingHandlers.css.update(element, cssSettingsAccessor); if (!config.errorsAsTitle) { return; } - var origTitle = ko.validation.utils.getAttribute(element, 'data-orig-title'), - elementTitle = element.title, - titleIsErrorMsg = ko.validation.utils.getAttribute(element, 'data-orig-title') === "true"; + ko.bindingHandlers.attr.update(element, function () { + var + hasModification = !config.errorsAsTitleOnModified || isModified, + title = kv.utils.getOriginalElementTitle(element); - var errorMsgTitleAccessor = function () { - if (!config.errorsAsTitleOnModified || isModified) { - if (!isValid) { - return { title: obsv.error, 'data-orig-title': ko.validation.utils.getOriginalElementTitle(element) }; - } else { - return { title: ko.validation.utils.getOriginalElementTitle(element), 'data-orig-title': null }; - } + if (hasModification && !isValid) { + return { title: obsv.error, 'data-orig-title': title }; + } else if (!hasModification || isValid) { + return { title: title, 'data-orig-title': null }; } - }; - ko.bindingHandlers.attr.update(element, errorMsgTitleAccessor); + }); } }; @@ -851,13 +968,13 @@ ko.bindingHandlers['validationElement'] = { ko.bindingHandlers['validationOptions'] = (function () { return { init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { - var options = ko.utils.unwrapObservable(valueAccessor()); + var options = unwrap(valueAccessor()); if (options) { - var newConfig = ko.utils.extend({}, ko.validation.configuration); - ko.utils.extend(newConfig, options); + var newConfig = extend({}, kv.configuration); + extend(newConfig, options); //store the validation options on the node so we can retrieve it later - ko.validation.utils.setDomData(element, newConfig); + kv.utils.setDomData(element, newConfig); } } }; @@ -875,11 +992,11 @@ ko.bindingHandlers['validationOptions'] = (function () { // } // )}; ko.extenders['validation'] = function (observable, rules) { // allow single rule or array - ko.utils.arrayForEach(ko.validation.utils.isArray(rules) ? rules : [rules], function (rule) { + forEach(kv.utils.isArray(rules) ? rules : [rules], function (rule) { // the 'rule' being passed in here has no name to identify a core Rule, // so we add it as an anonymous rule // If the developer is wanting to use a core Rule, but use a different message see the 'addExtender' logic for examples - ko.validation.addAnonymousRule(observable, rule); + kv.addAnonymousRule(observable, rule); }); return observable; }; @@ -891,8 +1008,20 @@ ko.extenders['validation'] = function (observable, rules) { // allow single rule // // 2. test.extend({validatable: false}); // this will remove the validation properties from the Observable object should you need to do that. -ko.extenders['validatable'] = function (observable, enable) { - if (enable && !ko.validation.utils.isValidatable(observable)) { +ko.extenders['validatable'] = function (observable, options) { + if (!kv.utils.isObject(options)) { + options = { enable: options }; + } + + if (!('enable' in options)) { + options.enable = true; + } + + if (options.enable && !kv.utils.isValidatable(observable)) { + var config = kv.configuration.validate || {}; + var validationOptions = { + throttleEvaluation : options.throttle || config.throttle + }; observable.error = ko.observable(null); // holds the error message, we only need one since we stop processing validators when one is invalid @@ -910,21 +1039,8 @@ ko.extenders['validatable'] = function (observable, enable) { observable.isModified = ko.observable(false); - // we use a computed here to ensure that anytime a dependency changes, the - // validation logic evaluates - var h_obsValidationTrigger = ko.computed(function () { - var obs = observable(), - ruleContexts = observable.rules(); - - ko.validation.validateObservable(observable); - - return true; - }); - // a semi-protected observable - observable.isValid = ko.computed(function () { - return observable.__valid__(); - }); + observable.isValid = ko.computed(observable.__valid__); //manually set error state observable.setError = function (error) { @@ -943,6 +1059,21 @@ ko.extenders['validatable'] = function (observable, enable) { observable.isModified(true); }); + // we use a computed here to ensure that anytime a dependency changes, the + // validation logic evaluates + var h_obsValidationTrigger = ko.computed(extend({ + read: function () { + var obs = observable(), + ruleContexts = observable.rules(); + + kv.validateObservable(observable); + + return true; + } + }, validationOptions)); + + extend(h_obsValidationTrigger, validationOptions); + observable._disposeValidation = function () { //first dispose of the subscriptions observable.isValid.dispose(); @@ -960,11 +1091,8 @@ ko.extenders['validatable'] = function (observable, enable) { delete observable['__valid__']; delete observable['isModified']; }; - } else if (enable === false && ko.validation.utils.isValidatable(observable)) { - - if (observable._disposeValidation) { - observable._disposeValidation(); - } + } else if (options.enable === false && observable._disposeValidation) { + observable._disposeValidation(); } return observable; }; @@ -974,8 +1102,7 @@ function validateSync(observable, rule, ctx) { if (!rule.validator(observable(), ctx.params === undefined ? true : ctx.params)) { // default param is true, eg. required = true //not valid, so format the error message and stick it in the 'error' variable - observable.error(ko.validation.formatMessage(ctx.message || rule.message, ctx.params)); - observable.__valid__(false); + observable.setError(kv.formatMessage(ctx.message || rule.message, ctx.params)); return false; } else { return true; @@ -1007,7 +1134,7 @@ function validateAsync(observable, rule, ctx) { if (!isValid) { //not valid, so format the error message and stick it in the 'error' variable - observable.error(ko.validation.formatMessage(msg || ctx.message || rule.message, ctx.params)); + observable.error(kv.formatMessage(msg || ctx.message || rule.message, ctx.params)); observable.__valid__(isValid); } @@ -1019,7 +1146,7 @@ function validateAsync(observable, rule, ctx) { rule.validator(observable(), ctx.params || true, callBack); } -ko.validation.validateObservable = function (observable) { +kv.validateObservable = function (observable) { var i = 0, rule, // the rule validator to execute ctx, // the current Rule Context for the loop @@ -1037,7 +1164,7 @@ ko.validation.validateObservable = function (observable) { } //get the core Rule to use for validation - rule = ko.validation.rules[ctx.rule]; + rule = kv.rules[ctx.rule]; if (rule['async'] || ctx['async']) { //run async validation @@ -1051,19 +1178,19 @@ ko.validation.validateObservable = function (observable) { } } //finally if we got this far, make the observable valid again! - observable.error(null); - observable.__valid__(true); + observable.clearError(); return true; -};; +}; +; //quick function to override rule messages -ko.validation.localize = function (msgTranslations) { +kv.localize = function (msgTranslations) { var msg, rule; //loop the properties in the object and assign the msg to the rule for (rule in msgTranslations) { - if (ko.validation.rules.hasOwnProperty(rule)) { - ko.validation.rules[rule].message = msgTranslations[rule]; + if (kv.rules.hasOwnProperty(rule)) { + kv.rules[rule].message = msgTranslations[rule]; } } };;ko.applyBindingsWithValidation = function (viewModel, rootNode, options) { @@ -1083,9 +1210,9 @@ ko.validation.localize = function (msgTranslations) { } } - ko.validation.init(); + kv.init(); - if (config) { ko.validation.utils.setDomData(node, config); } + if (config) { kv.utils.setDomData(node, config); } ko.applyBindings(viewModel, rootNode); }; @@ -1094,19 +1221,21 @@ ko.validation.localize = function (msgTranslations) { var origApplyBindings = ko.applyBindings; ko.applyBindings = function (viewModel, rootNode) { - ko.validation.init(); + kv.init(); origApplyBindings(viewModel, rootNode); }; ko.validatedObservable = function (initialValue) { - if (!ko.validation.utils.isObject(initialValue)) { return ko.observable(initialValue).extend({ validatable: true }); } + if (!kv.utils.isObject(initialValue)) { return ko.observable(initialValue).extend({ validatable: true }); } var obsv = ko.observable(initialValue); - obsv.errors = ko.validation.group(initialValue); - obsv.isValid = ko.computed(function () { - return obsv.errors().length === 0; + obsv.isValid = ko.observable(); + obsv.errors = kv.group(initialValue); + obsv.errors.subscribe(function (errors) { + obsv.isValid(errors.length === 0); }); return obsv; -};;})); \ No newline at end of file +}; +;})); \ No newline at end of file diff --git a/Dist/knockout.validation.min.js b/Dist/knockout.validation.min.js index 614e3730..5c1fa7d1 100644 --- a/Dist/knockout.validation.min.js +++ b/Dist/knockout.validation.min.js @@ -5,4 +5,4 @@ Description: Validation Library for KnockoutJS =============================================================================== */ -!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(b,c,d){return c.validator(b(),void 0===d.params?!0:d.params)?!0:(b.error(a.validation.formatMessage(d.message||c.message,d.params)),b.__valid__(!1),!1)}function d(b,c,d){b.isValidating(!0);var e=function(e){var f=!1,g="";return b.__valid__()?(e.message?(f=e.isValid,g=e.message):f=e,f||(b.error(a.validation.formatMessage(g||d.message||c.message,d.params)),b.__valid__(f)),b.isValidating(!1),void 0):(b.isValidating(!1),void 0)};c.validator(b(),d.params||!0,e)}if(void 0===typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var e={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",grouping:{deep:!1,observable:!0}},f=a.utils.extend({},e);f.html5Attributes=["required","pattern","min","max","step"],f.html5InputTypes=["email","number","date"],f.reset=function(){a.utils.extend(f,e)},a.validation.configuration=f,a.validation.utils=function(){var b=(new Date).getTime(),c={},d="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return a&&a.rules&&a.isValid&&a.isModified},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return b+=1},getConfigOptions:function(b){var c=a.validation.utils.contextFor(b);return c||a.validation.configuration},setDomData:function(b,e){var f=b[d];f||(b[d]=f=a.validation.utils.newId()),c[f]=e},getDomData:function(a){var b=a[d];return b?c[b]:void 0},contextFor:function(b){switch(b.nodeType){case 1:case 8:var c=a.validation.utils.getDomData(b);if(c)return c;if(b.parentNode)return a.validation.utils.contextFor(b.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(b){var c=a.validation.utils.getAttribute(b,"data-orig-title"),d=b.title,e=a.validation.utils.hasAttribute(b,"data-orig-title");return e?c:d},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)}}}();var g=function(){var b=0,c=a.validation.configuration,d=a.validation.utils;return{init:function(d,e){b>0&&!e||(d=d||{},d.errorElementClass=d.errorElementClass||d.errorClass||c.errorElementClass,d.errorMessageClass=d.errorMessageClass||d.errorClass||c.errorMessageClass,a.utils.extend(c,d),c.registerExtenders&&a.validation.registerExtenders(),b=1)},configure:function(b){a.validation.init(b)},reset:a.validation.configuration.reset,group:function(b,e){e=a.utils.extend(a.utils.extend({},c.grouping),e);var f=a.observableArray([]),g=null,h=[],i=function(){e.deep&&a.utils.arrayForEach(h,function(a){delete a.__kv_traversed})},j=function k(b,c){var g=[],i=a.utils.unwrapObservable(b);b.__kv_traversed!==!0&&(e.deep&&(b.__kv_traversed=!0,h.push(b)),c=void 0!==c?c:e.deep?1:-1,a.isObservable(b)&&(b.isValid||b.extend({validatable:!0}),f.push(b)),i&&(d.isArray(i)?g=i:d.isObject(i)&&(g=d.values(i))),0!==c&&a.utils.arrayForEach(g,function(a){a&&!a.nodeType&&k(a,c+1)}))};return e.observable?(j(b),i(),g=a.computed(function(){var b=[];return a.utils.arrayForEach(f(),function(a){a.isValid()||b.push(a.error)}),b})):g=function(){var c=[];return f([]),j(b),i(),a.utils.arrayForEach(f(),function(a){a.isValid()||c.push(a.error)}),c},g.showAllMessages=function(b){void 0===b&&(b=!0),g(),a.utils.arrayForEach(f(),function(a){a.isModified(b)})},b.errors=g,b.isValid=function(){return 0===b.errors().length},b.isAnyMessageShown=function(){var b=!1;return g(),a.utils.arrayForEach(f(),function(a){!a.isValid()&&a.isModified()&&(b=!0)}),b},g},formatMessage:function(b,c){return"function"==typeof b?b(c):b.replace(/\{0\}/gi,a.utils.unwrapObservable(c))},addRule:function(a,b){return a.extend({validatable:!0}),a.rules.push(b),a},addAnonymousRule:function(b,c){var e=d.newId();void 0===c.message&&(c.message="Error"),a.validation.rules[e]=c,a.validation.addRule(b,{rule:e,params:c.params})},addExtender:function(b){a.extenders[b]=function(c,e){return e.message||e.onlyIf?a.validation.addRule(c,{rule:b,message:e.message,params:d.isEmptyVal(e.params)?!0:e.params,condition:e.onlyIf}):a.validation.addRule(c,{rule:b,params:e})}},registerExtenders:function(){if(c.registerExtenders)for(var b in a.validation.rules)a.validation.rules.hasOwnProperty(b)&&(a.extenders[b]||a.validation.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=d.getConfigOptions(a).errorMessageClass,d.insertAfter(a,b),b},parseInputValidationAttributes:function(b,c){a.utils.arrayForEach(a.validation.configuration.html5Attributes,function(e){d.hasAttribute(b,e)&&a.validation.addRule(c(),{rule:e,params:b.getAttribute(e)||!0})});var e=b.getAttribute("type");a.utils.arrayForEach(a.validation.configuration.html5InputTypes,function(b){b===e&&a.validation.addRule(c(),{rule:"date"===b?"dateISO":b,params:!0})})},writeInputValidationAttributes:function(b,c){var d=c();if(d&&d.rules){var e=d.rules();a.utils.arrayForEach(a.validation.configuration.html5Attributes,function(c){var d,f=a.utils.arrayFirst(e,function(a){return a.rule.toLowerCase()===c.toLowerCase()});f&&(d=f.params,"pattern"===f.rule&&f.params instanceof RegExp&&(d=f.params.source),b.setAttribute(c,d))}),e=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}}}}();a.utils.extend(a.validation,g),a.validation.rules={},a.validation.rules.required={validator:function(a,b){var c,d=/^\s+|\s+$/g;return void 0===a||null===a?!b:(c=a,"string"==typeof a&&(c=a.replace(d,"")),b?(c+"").length>0:!0)},message:"This field is required."},a.validation.rules.min={validator:function(b,c){return a.validation.utils.isEmptyVal(b)||b>=c},message:"Please enter a value greater than or equal to {0}."},a.validation.rules.max={validator:function(b,c){return a.validation.utils.isEmptyVal(b)||c>=b},message:"Please enter a value less than or equal to {0}."},a.validation.rules.minLength={validator:function(b,c){return a.validation.utils.isEmptyVal(b)||b.length>=c},message:"Please enter at least {0} characters."},a.validation.rules.maxLength={validator:function(b,c){return a.validation.utils.isEmptyVal(b)||b.length<=c},message:"Please enter no more than {0} characters."},a.validation.rules.pattern={validator:function(b,c){return a.validation.utils.isEmptyVal(b)||null!==b.toString().match(c)},message:"Please check this value."},a.validation.rules.step={validator:function(b,c){if(a.validation.utils.isEmptyVal(b)||"any"===c)return!0;var d=100*b%(100*c);return Math.abs(d)<1e-5||Math.abs(1-d)<1e-5},message:"The value must increment by {0}"},a.validation.rules.email={validator:function(b,c){return c?a.validation.utils.isEmptyVal(b)||c&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(b):!0},message:"Please enter a proper email address"},a.validation.rules.date={validator:function(b,c){return c?a.validation.utils.isEmptyVal(b)||c&&!/Invalid|NaN/.test(new Date(b)):!0},message:"Please enter a proper date"},a.validation.rules.dateISO={validator:function(b,c){return c?a.validation.utils.isEmptyVal(b)||c&&/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(b):!0},message:"Please enter a proper date"},a.validation.rules.number={validator:function(b,c){return c?a.validation.utils.isEmptyVal(b)||c&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(b):!0},message:"Please enter a number"},a.validation.rules.digit={validator:function(b,c){return c?a.validation.utils.isEmptyVal(b)||c&&/^\d+$/.test(b):!0},message:"Please enter a digit"},a.validation.rules.phoneUS={validator:function(b,c){return c?a.validation.utils.isEmptyVal(b)?!0:"string"!=typeof b?!1:(b=b.replace(/\s+/g,""),c&&b.length>9&&b.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number"},a.validation.rules.equal={validator:function(b,c){var d=c;return b===a.validation.utils.getValue(d)},message:"Values must equal"},a.validation.rules.notEqual={validator:function(b,c){var d=c;return b!==a.validation.utils.getValue(d)},message:"Please choose another value."},a.validation.rules.unique={validator:function(b,c){var d=a.validation.utils.getValue(c.collection),e=a.validation.utils.getValue(c.externalValue),f=0;return b&&d?(a.utils.arrayFilter(a.utils.unwrapObservable(d),function(a){b===(c.valueAccessor?c.valueAccessor(a):a)&&f++}),(void 0!==e&&b!==e?1:2)>f):!0},message:"Please make sure the value is unique."},function(){a.validation.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=a.validation.utils.getConfigOptions(b);if(d.parseInputAttributes&&a.validation.utils.async(function(){a.validation.parseInputValidationAttributes(b,c)}),d.insertMessages&&a.validation.utils.isValidatable(c())){var e=a.validation.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:c()},null,e,"replaceNode"):a.applyBindingsToNode(e,{validationMessage:c()})}d.writeInputAttributes&&a.validation.utils.isValidatable(c())&&a.validation.writeInputValidationAttributes(b,c),d.decorateElement&&a.validation.utils.isValidatable(c())&&a.applyBindingsToNode(b,{validationElement:c()})},update:function(){}}}(),a.validation.makeBindingHandlerValidatable("value"),a.validation.makeBindingHandlerValidatable("checked"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=a.validation.utils.getConfigOptions(b),f=(a.utils.unwrapObservable(d),!1),g=!1;d.extend({validatable:!0}),f=d.isModified(),g=d.isValid();var h=function(){return!e.messagesOnModified||f?g?null:d.error:null},i=function(){return!e.messagesOnModified||f?!g:!1};a.bindingHandlers.text.update(b,h),a.bindingHandlers.visible.update(b,i)}},a.bindingHandlers.validationElement={update:function(b,c){var d=c(),e=a.validation.utils.getConfigOptions(b),f=(a.utils.unwrapObservable(d),!1),g=!1;d.extend({validatable:!0}),f=d.isModified(),g=d.isValid();var h=function(){var a={},b=!e.decorateElementOnModified||f?!g:!1;return e.decorateElement||(b=!1),a[e.errorElementClass]=b,a};if(a.bindingHandlers.css.update(b,h),e.errorsAsTitle){a.validation.utils.getAttribute(b,"data-orig-title"),b.title,"true"===a.validation.utils.getAttribute(b,"data-orig-title");var i=function(){return!e.errorsAsTitleOnModified||f?g?{title:a.validation.utils.getOriginalElementTitle(b),"data-orig-title":null}:{title:d.error,"data-orig-title":a.validation.utils.getOriginalElementTitle(b)}:void 0};a.bindingHandlers.attr.update(b,i)}}},a.bindingHandlers.validationOptions=function(){return{init:function(b,c){var d=a.utils.unwrapObservable(c());if(d){var e=a.utils.extend({},a.validation.configuration);a.utils.extend(e,d),a.validation.utils.setDomData(b,e)}}}}(),a.extenders.validation=function(b,c){return a.utils.arrayForEach(a.validation.utils.isArray(c)?c:[c],function(c){a.validation.addAnonymousRule(b,c)}),b},a.extenders.validatable=function(b,c){if(c&&!a.validation.utils.isValidatable(b)){b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1);var d=a.computed(function(){return b(),b.rules(),a.validation.validateObservable(b),!0});b.isValid=a.computed(function(){return b.__valid__()}),b.setError=function(a){b.error(a),b.__valid__(!1)},b.clearError=function(){b.error(null),b.__valid__(!0)};var e=b.subscribe(function(){b.isModified(!0)});b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified._subscriptions.change=[],b.isValidating._subscriptions.change=[],b.__valid__._subscriptions.change=[],e.dispose(),d.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c===!1&&a.validation.utils.isValidatable(b)&&b._disposeValidation&&b._disposeValidation();return b},a.validation.validateObservable=function(b){for(var e,f,g=0,h=b.rules(),i=h.length;i>g;g++)if(f=h[g],!f.condition||f.condition())if(e=a.validation.rules[f.rule],e.async||f.async)d(b,e,f);else if(!c(b,e,f))return!1;return b.error(null),b.__valid__(!0),!0},a.validation.localize=function(b){var c;for(c in b)a.validation.rules.hasOwnProperty(c)&&(a.validation.rules[c].message=b[c])},a.applyBindingsWithValidation=function(b,c,d){var e,f,g=arguments.length;g>2?(e=c,f=d):2>g?e=document.body:arguments[1].nodeType?e=c:f=arguments[1],a.validation.init(),f&&a.validation.utils.setDomData(e,f),a.applyBindings(b,c)};var h=a.applyBindings;a.applyBindings=function(b,c){a.validation.init(),h(b,c)},a.validatedObservable=function(b){if(!a.validation.utils.isObject(b))return a.observable(b).extend({validatable:!0});var c=a.observable(b);return c.errors=a.validation.group(b),c.isValid=a.computed(function(){return 0===c.errors().length}),c}}); \ No newline at end of file +!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for week input. Should look like "+"'2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for month input. Should look like "+"'2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:c.params)?!0:(a.setError(f.formatMessage(c.message||b.message,c.params)),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,c.params)),a.__valid__(e)),a.isValidating(!1),void 0):(a.isValidating(!1),void 0)};b.validator(a(),c.params||!0,d)}if(void 0===typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",grouping:{deep:!1,observable:!0},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return a&&a.rules&&a.isValid&&a.isModified},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)}}}();var m=function(){var b=0,c=f.configuration,d=f.utils;return{init:function(a,d){b>0&&!d||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||c.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||c.errorMessageClass,j(c,a),c.registerExtenders&&f.registerExtenders(),b=1)},configure:function(a){f.init(a)},reset:f.configuration.reset,group:function(b,e){e=j(j({},c.grouping),e);var f=a.observableArray([]),g=null,k=[],l=function(){e.deep&&i(k,function(a){delete a.__kv_traversed})},m=function n(b,c){var g=[],j=h(b);b.__kv_traversed!==!0&&(e.deep&&(b.__kv_traversed=!0,k.push(b)),c=void 0!==c?c:e.deep?1:-1,a.isObservable(b)&&(b.isValid||b.extend({validatable:!0}),f.push(b)),j&&(d.isArray(j)?g=j:d.isObject(j)&&(g=d.values(j))),0!==c&&i(g,function(a){a&&!a.nodeType&&n(a,c+1)}))};return e.observable?(m(b),l(),g=a.computed(function(){var a=[];return i(f(),function(b){b.isValid()||a.push(b.error)}),a})):g=function(){var a=[];return f([]),m(b),l(),i(f(),function(b){b.isValid()||a.push(b.error)}),a},g.showAllMessages=function(a){void 0===a&&(a=!0),g(),i(f(),function(b){b.isModified(a)})},b.errors=g,b.isValid=function(){return 0===b.errors().length},b.isAnyMessageShown=function(){var a=!1;return g(),i(f(),function(b){!b.isValid()&&b.isModified()&&(a=!0)}),a},g},formatMessage:function(a,b){return"function"==typeof a?a(b):a.replace(/\{0\}/gi,h(b))},addRule:function(a,b){return a.extend({validatable:!0}),a.rules.push(b),a},addAnonymousRule:function(a,b){var c=d.newId();void 0===b.message&&(b.message="Error"),f.rules[c]=b,f.addRule(a,{rule:c,params:b.params})},addExtender:function(b){a.extenders[b]=function(a,c){return c.message||c.onlyIf?f.addRule(a,{rule:b,message:c.message,params:d.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(c.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=d.getConfigOptions(a).errorMessageClass,d.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(d.hasAttribute(a,c)){var e=a.getAttribute(c)||!0;if("min"===c||"max"===c){var g=a.getAttribute("type");"undefined"!=typeof g&&g||(g="text"),e={typeAttr:g,value:e}}f.addRule(b(),{rule:c,params:e})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(a,b){var c=b();if(c&&c.rules){var d=c.rules();i(f.configuration.html5Attributes,function(b){var c,e=g.arrayFirst(d,function(a){return a.rule.toLowerCase()===b.toLowerCase()});e&&(c=e.params,"pattern"===e.rule&&e.params instanceof RegExp&&(c=e.params.source),a.setAttribute(b,c))}),d=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}}}}();j(a.validation,m),f.rules={},f.rules.required={validator:function(a,b){var c,d=/^\s+|\s+$/g;return void 0===a||null===a?!b:(c=a,"string"==typeof a&&(c=a.replace(d,"")),b?(c+"").length>0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){return f.utils.isEmptyVal(a)||a.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){return f.utils.isEmptyVal(a)||a.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}"},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address"},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date"},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(a):!0},message:"Please enter a proper date"},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number"},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit"},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number"},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal"},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(h(c),function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(void 0!==d&&a!==d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})},update:function(){}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),g=(h(d),!1),i=!1;d.extend({validatable:!0}),g=d.isModified(),i=d.isValid();var j=function(){return!e.messagesOnModified||g?i?null:d.error:null},k=function(){return!e.messagesOnModified||g?!i:!1};a.bindingHandlers.text.update(b,j),a.bindingHandlers.visible.update(b,k)}},a.bindingHandlers.validationElement={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),g=(h(d),!1),i=!1;d.extend({validatable:!0}),g=d.isModified(),i=d.isValid();var j=function(){var a={},b=!e.decorateElementOnModified||g?!i:!1;return e.decorateElement||(b=!1),a[e.errorElementClass]=b,a};a.bindingHandlers.css.update(b,j),e.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!e.errorsAsTitleOnModified||g,c=f.utils.getOriginalElementTitle(b);return a&&!i?{title:d.error,"data-orig-title":c}:!a||i?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){b.error(a),b.__valid__(!1)},b.clearError=function(){b.error(null),b.__valid__(!0)};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){return b(),b.rules(),f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified._subscriptions.change=[],b.isValidating._subscriptions.change=[],b.__valid__._subscriptions.change=[],g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=f.rules[c.rule],b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0},f.localize=function(a){var b;for(b in a)f.rules.hasOwnProperty(b)&&(f.rules[b].message=a[b])},a.applyBindingsWithValidation=function(b,c,d){var e,g,h=arguments.length;h>2?(e=c,g=d):2>h?e=document.body:arguments[1].nodeType?e=c:g=arguments[1],f.init(),g&&f.utils.setDomData(e,g),a.applyBindings(b,c)};var n=a.applyBindings;a.applyBindings=function(a,b){f.init(),n(a,b)},a.validatedObservable=function(b){if(!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var c=a.observable(b);return c.isValid=a.observable(),c.errors=f.group(b),c.errors.subscribe(function(a){c.isValid(0===a.length)}),c}}); \ No newline at end of file diff --git a/Lib/knockout-latest.debug.js b/Lib/knockout-latest.debug.js index 9fe33c8f..77bb4cff 100644 --- a/Lib/knockout-latest.debug.js +++ b/Lib/knockout-latest.debug.js @@ -1,3679 +1,4225 @@ -// Knockout JavaScript library v2.3.0 +// Knockout JavaScript library v3.0.0 // (c) Steven Sanderson - http://knockoutjs.com/ // License: MIT (http://www.opensource.org/licenses/mit-license.php) +(function(){ +var DEBUG=true; +(function(undefined){ + // (0, eval)('this') is a robust way of getting a reference to the global object + // For details, see http://stackoverflow.com/questions/14119988/return-this-0-evalthis/14120023#14120023 + var window = this || (0, eval)('this'), + document = window['document'], + navigator = window['navigator'], + jQuery = window["jQuery"], + JSON = window["JSON"]; +(function(factory) { + // Support three module loading scenarios + if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') { + // [1] CommonJS/Node.js + var target = module['exports'] || exports; // module.exports is for Node.js + factory(target); + } else if (typeof define === 'function' && define['amd']) { + // [2] AMD anonymous module + define(['exports'], factory); + } else { + // [3] No module loader (plain - + From 0739f71a88ca791139a016e6f56acd42728eacd9 Mon Sep 17 00:00:00 2001 From: barkbarkuk Date: Wed, 27 Nov 2013 10:37:06 +0000 Subject: [PATCH 067/165] Fix issue of using private ko.utils.setTextContent method --- Dist/knockout.validation.js | 2 +- Src/bindingHandlers.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Dist/knockout.validation.js b/Dist/knockout.validation.js index 6a6773cc..57591a55 100644 --- a/Dist/knockout.validation.js +++ b/Dist/knockout.validation.js @@ -951,7 +951,7 @@ ko.bindingHandlers['validationMessage'] = { // individual error message, if modi if (config.allowHtmlMessages) { koUtils.setHtml(element, error); } else { - koUtils.setTextContent(element, error); + ko.bindingHandlers.text.update(element, function () { return error; }); } if (isCurrentlyVisible && !isVisible) { diff --git a/Src/bindingHandlers.js b/Src/bindingHandlers.js index 1d774b7e..91359bb0 100644 --- a/Src/bindingHandlers.js +++ b/Src/bindingHandlers.js @@ -74,7 +74,7 @@ ko.bindingHandlers['validationMessage'] = { // individual error message, if modi if (config.allowHtmlMessages) { ko.utils.setHtml(element, error); } else { - ko.utils.setTextContent(element, error); + ko.bindingHandlers.text.update(element, function () { return error; }); } if (isCurrentlyVisible && !isVisible) { From f2184aee85bef5f3bd16292b1ee1f99daddee63b Mon Sep 17 00:00:00 2001 From: barkbarkuk Date: Wed, 27 Nov 2013 10:51:15 +0000 Subject: [PATCH 068/165] Made check for subscriptions before trying to clean them (making tests green). --- Dist/knockout.validation.js | 12 +++++++++--- Dist/knockout.validation.min.js | 2 +- Src/extenders.js | 12 +++++++++--- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/Dist/knockout.validation.js b/Dist/knockout.validation.js index 57591a55..68dd5dfa 100644 --- a/Dist/knockout.validation.js +++ b/Dist/knockout.validation.js @@ -1131,9 +1131,15 @@ ko.extenders['validatable'] = function (observable, options) { //first dispose of the subscriptions observable.isValid.dispose(); observable.rules.removeAll(); - observable.isModified._subscriptions['change'] = []; - observable.isValidating._subscriptions['change'] = []; - observable.__valid__._subscriptions['change'] = []; + if (observable.isModified.getSubscriptionsCount() > 0) { + observable.isModified._subscriptions['change'] = []; + } + if (observable.isValidating.getSubscriptionsCount() > 0) { + observable.isValidating._subscriptions['change'] = []; + } + if (observable.__valid__.getSubscriptionsCount() > 0) { + observable.__valid__._subscriptions['change'] = []; + } h_change.dispose(); h_obsValidationTrigger.dispose(); diff --git a/Dist/knockout.validation.min.js b/Dist/knockout.validation.min.js index 4ed6ce95..6b2a96b1 100644 --- a/Dist/knockout.validation.min.js +++ b/Dist/knockout.validation.min.js @@ -5,4 +5,4 @@ Description: Validation Library for KnockoutJS =============================================================================== */ -!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for week input. Should look like "+"'2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for month input. Should look like "+"'2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:h(c.params))?!0:(a.setError(f.formatMessage(c.message||b.message,h(c.params))),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,h(c.params))),a.__valid__(e)),a.isValidating(!1),void 0):(a.isValidating(!1),void 0)};b.validator(a(),h(c.params||!0),d)}if(void 0===typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return!!(a&&a.rules&&a.isValid&&a.isModified)},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},forEach:function(a,b){if(f.utils.isArray(a))return i(a,b);for(var c in a)a.hasOwnProperty(c)&&b(a[c],c)}}}();var m=function(){function b(c,d,e){var f=[],g=h(c);d.flagged||(d.flagged=[]),d.toValidate||(d.toValidate=[]),c.__kv_traversed!==!0&&(d.deep&&(c.__kv_traversed=!0,d.flagged.push(c)),e=void 0!==e?e:d.deep?1:-1,a.isObservable(c)&&(c.isValid||c.extend({validatable:!0}),d.toValidate.push(c)),g&&(k.isArray(g)||k.isObject(g))&&(f=g),0!==e&&k.forEach(f,function(a){a&&!a.nodeType&&b(a,d,e+1)}))}function c(a){var b=[];return i(a,function(a){a.isValid()||b.push(a.error)}),b}var d=0,e=f.configuration,k=f.utils;return{init:function(a,b){d>0&&!b||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||e.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||e.errorMessageClass,j(e,a),e.registerExtenders&&f.registerExtenders(),d=1)},configure:function(a){f.init(a)},reset:f.configuration.reset,group:function(d,f){f=j(j({},e.grouping),f);var h=a.observableArray([]),k=null,l=function(){f.deep&&(i(f.flagged,function(a){delete a.__kv_traversed}),f.flagged.length=0),f.toValidate=[]};return f.observable?(b(d,f),h(f.toValidate),l(),k=a.computed(function(){return c(h())})):k=function(){return b(d,f),h(f.toValidate),l(),c(h())},k.showAllMessages=function(a){void 0===a&&(a=!0),k(),i(h(),function(b){b.isModified(a)})},d.errors=k,d.isValid=function(){return 0===d.errors().length},d.isAnyMessageShown=function(){var a=!1;return k(),a=!!g.arrayFirst(h(),function(a){return!a.isValid()&&a.isModified()})},k},formatMessage:function(a,b){return"function"==typeof a?a(b):a.replace(/\{0\}/gi,h(b))},addRule:function(a,b){return a.extend({validatable:!0}),a.rules.push(b),a},addAnonymousRule:function(a,b){void 0===b.message&&(b.message="Error"),f.addRule(a,b)},addExtender:function(b){a.extenders[b]=function(a,c){return c&&(c.message||c.onlyIf)?f.addRule(a,{rule:b,message:c.message,params:k.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(e.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=k.getConfigOptions(a).errorMessageClass,k.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(k.hasAttribute(a,c)){var d=a.getAttribute(c)||!0;if("min"===c||"max"===c){var e=a.getAttribute("type");"undefined"!=typeof e&&e||(e="text"),d={typeAttr:e,value:d}}f.addRule(b(),{rule:c,params:d})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(a,b){var c=b();if(c&&c.rules){var d=c.rules();i(f.configuration.html5Attributes,function(b){var c,e=g.arrayFirst(d,function(a){return a.rule.toLowerCase()===b.toLowerCase()});e&&(c=e.params,"pattern"===e.rule&&e.params instanceof RegExp&&(c=e.params.source),a.setAttribute(b,c))}),d=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var d=function(b,c){if(b&&c)for(var e in c)if(c.hasOwnProperty(e)){var g=c[e];if(b[e]){var i=b[e],j=h(i),l={},m={};for(var n in g)g.hasOwnProperty(n)&&(f.rules[n]?l[n]=g[n]:m[n]=g[n]);if(a.isObservable(i)&&i.extend(l),j&&k.isArray(j))for(var o=0;o0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){return f.utils.isEmptyVal(a)||a.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){return f.utils.isEmptyVal(a)||a.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}"},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address"},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date"},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(a):!0},message:"Please enter a proper date"},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number"},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit"},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number"},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal"},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(c,function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateInputElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.validationMessage={update:function(a,b){var c=b(),d=f.utils.getConfigOptions(a),e=(h(c),!1),i=!1;if(!c.isValid||!c.isModified)throw new Error("Observable is not validatable");e=c.isModified(),i=c.isValid();var j=null;(!d.messagesOnModified||e)&&(j=i?null:c.error);var k=!d.messagesOnModified||e?!i:!1,l="none"!==a.style.display;d.allowHtmlMessages?g.setHtml(a,j):g.setTextContent(a,j),l&&!k?a.style.display="none":!l&&k&&(a.style.display="")}},a.bindingHandlers.validationElement={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),g=(h(d),!1),i=!1;if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");g=d.isModified(),i=d.isValid();var j=function(){var a={},b=!e.decorateElementOnModified||g?!i:!1;return a[e.errorElementClass]=b,a};a.bindingHandlers.css.update(b,j),e.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!e.errorsAsTitleOnModified||g,c=f.utils.getOriginalElementTitle(b);return a&&!i?{title:d.error,"data-orig-title":c}:!a||i?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){b.error(a),b.__valid__(!1)},b.clearError=function(){return b.error(null),b.__valid__(!0),b};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){return b(),b.rules(),f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified._subscriptions.change=[],b.isValidating._subscriptions.change=[],b.__valid__._subscriptions.change=[],g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=c.rule?f.rules[c.rule]:c,b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0},f.localize=function(a){var b;for(b in a)f.rules.hasOwnProperty(b)&&(f.rules[b].message=a[b])},a.applyBindingsWithValidation=function(b,c,d){var e,g,h=arguments.length;h>2?(e=c,g=d):2>h?e=document.body:arguments[1].nodeType?e=c:g=arguments[1],f.init(),g&&f.utils.setDomData(e,g),a.applyBindings(b,c)};var n=a.applyBindings;a.applyBindings=function(a,b){f.init(),n(a,b)},a.validatedObservable=function(b){if(!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var c=a.observable(b);return c.isValid=a.observable(),c.errors=f.group(b),c.errors.subscribe(function(a){c.isValid(0===a.length)}),c}}); \ No newline at end of file +!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for week input. Should look like '2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for month input. Should look like '2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:h(c.params))?!0:(a.setError(f.formatMessage(c.message||b.message,h(c.params))),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,h(c.params))),a.__valid__(e)),a.isValidating(!1),void 0):(a.isValidating(!1),void 0)};b.validator(a(),h(c.params||!0),d)}if(void 0===typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return!!(a&&a.rules&&a.isValid&&a.isModified)},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},forEach:function(a,b){if(f.utils.isArray(a))return i(a,b);for(var c in a)a.hasOwnProperty(c)&&b(a[c],c)}}}();var m=function(){function b(c,d,e){var f=[],g=h(c);d.flagged||(d.flagged=[]),d.toValidate||(d.toValidate=[]),c.__kv_traversed!==!0&&(d.deep&&(c.__kv_traversed=!0,d.flagged.push(c)),e=void 0!==e?e:d.deep?1:-1,a.isObservable(c)&&(c.isValid||c.extend({validatable:!0}),d.toValidate.push(c)),g&&(k.isArray(g)||k.isObject(g))&&(f=g),0!==e&&k.forEach(f,function(a){a&&!a.nodeType&&b(a,d,e+1)}))}function c(a){var b=[];return i(a,function(a){a.isValid()||b.push(a.error)}),b}var d=0,e=f.configuration,k=f.utils;return{init:function(a,b){d>0&&!b||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||e.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||e.errorMessageClass,j(e,a),e.registerExtenders&&f.registerExtenders(),d=1)},configure:function(a){f.init(a)},reset:f.configuration.reset,group:function(d,f){f=j(j({},e.grouping),f);var h=a.observableArray([]),k=null,l=function(){f.deep&&(i(f.flagged,function(a){delete a.__kv_traversed}),f.flagged.length=0),f.toValidate=[]};return f.observable?(b(d,f),h(f.toValidate),l(),k=a.computed(function(){return c(h())})):k=function(){return b(d,f),h(f.toValidate),l(),c(h())},k.showAllMessages=function(a){void 0===a&&(a=!0),k(),i(h(),function(b){b.isModified(a)})},d.errors=k,d.isValid=function(){return 0===d.errors().length},d.isAnyMessageShown=function(){var a=!1;return k(),a=!!g.arrayFirst(h(),function(a){return!a.isValid()&&a.isModified()})},k},formatMessage:function(a,b){return"function"==typeof a?a(b):a.replace(/\{0\}/gi,h(b))},addRule:function(a,b){return a.extend({validatable:!0}),a.rules.push(b),a},addAnonymousRule:function(a,b){void 0===b.message&&(b.message="Error"),f.addRule(a,b)},addExtender:function(b){a.extenders[b]=function(a,c){return c&&(c.message||c.onlyIf)?f.addRule(a,{rule:b,message:c.message,params:k.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(e.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=k.getConfigOptions(a).errorMessageClass,k.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(k.hasAttribute(a,c)){var d=a.getAttribute(c)||!0;if("min"===c||"max"===c){var e=a.getAttribute("type");"undefined"!=typeof e&&e||(e="text"),d={typeAttr:e,value:d}}f.addRule(b(),{rule:c,params:d})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(a,b){var c=b();if(c&&c.rules){var d=c.rules();i(f.configuration.html5Attributes,function(b){var c,e=g.arrayFirst(d,function(a){return a.rule.toLowerCase()===b.toLowerCase()});e&&(c=e.params,"pattern"===e.rule&&e.params instanceof RegExp&&(c=e.params.source),a.setAttribute(b,c))}),d=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var d=function(b,c){if(b&&c)for(var e in c)if(c.hasOwnProperty(e)){var g=c[e];if(b[e]){var i=b[e],j=h(i),l={},m={};for(var n in g)g.hasOwnProperty(n)&&(f.rules[n]?l[n]=g[n]:m[n]=g[n]);if(a.isObservable(i)&&i.extend(l),j&&k.isArray(j))for(var o=0;o0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){return f.utils.isEmptyVal(a)||a.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){return f.utils.isEmptyVal(a)||a.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}"},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address"},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date"},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(a):!0},message:"Please enter a proper date"},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number"},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit"},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number"},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal"},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(c,function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateInputElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),i=(h(d),!1),j=!1;if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");i=d.isModified(),j=d.isValid();var k=null;(!e.messagesOnModified||i)&&(k=j?null:d.error);var l=!e.messagesOnModified||i?!j:!1,m="none"!==b.style.display;e.allowHtmlMessages?g.setHtml(b,k):a.bindingHandlers.text.update(b,function(){return k}),m&&!l?b.style.display="none":!m&&l&&(b.style.display="")}},a.bindingHandlers.validationElement={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),g=(h(d),!1),i=!1;if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");g=d.isModified(),i=d.isValid();var j=function(){var a={},b=!e.decorateElementOnModified||g?!i:!1;return a[e.errorElementClass]=b,a};a.bindingHandlers.css.update(b,j),e.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!e.errorsAsTitleOnModified||g,c=f.utils.getOriginalElementTitle(b);return a&&!i?{title:d.error,"data-orig-title":c}:!a||i?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){b.error(a),b.__valid__(!1)},b.clearError=function(){return b.error(null),b.__valid__(!0),b};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){b(),b.rules();return f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified.getSubscriptionsCount()>0&&(b.isModified._subscriptions.change=[]),b.isValidating.getSubscriptionsCount()>0&&(b.isValidating._subscriptions.change=[]),b.__valid__.getSubscriptionsCount()>0&&(b.__valid__._subscriptions.change=[]),g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=c.rule?f.rules[c.rule]:c,b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0},f.localize=function(a){var b;for(b in a)f.rules.hasOwnProperty(b)&&(f.rules[b].message=a[b])},a.applyBindingsWithValidation=function(b,c,d){var e,g,h=arguments.length;h>2?(e=c,g=d):2>h?e=document.body:arguments[1].nodeType?e=c:g=arguments[1],f.init(),g&&f.utils.setDomData(e,g),a.applyBindings(b,c)};var n=a.applyBindings;a.applyBindings=function(a,b){f.init(),n(a,b)},a.validatedObservable=function(b){if(!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var c=a.observable(b);return c.isValid=a.observable(),c.errors=f.group(b),c.errors.subscribe(function(a){c.isValid(0===a.length)}),c}}); \ No newline at end of file diff --git a/Src/extenders.js b/Src/extenders.js index 8ebce66a..513a438a 100644 --- a/Src/extenders.js +++ b/Src/extenders.js @@ -98,9 +98,15 @@ ko.extenders['validatable'] = function (observable, options) { //first dispose of the subscriptions observable.isValid.dispose(); observable.rules.removeAll(); - observable.isModified._subscriptions['change'] = []; - observable.isValidating._subscriptions['change'] = []; - observable.__valid__._subscriptions['change'] = []; + if (observable.isModified.getSubscriptionsCount() > 0) { + observable.isModified._subscriptions['change'] = []; + } + if (observable.isValidating.getSubscriptionsCount() > 0) { + observable.isValidating._subscriptions['change'] = []; + } + if (observable.__valid__.getSubscriptionsCount() > 0) { + observable.__valid__._subscriptions['change'] = []; + } h_change.dispose(); h_obsValidationTrigger.dispose(); From e5fd8fd3dff2a82dcbe773e5ce493a6798da36af Mon Sep 17 00:00:00 2001 From: Steve Greatrex Date: Fri, 6 Dec 2013 09:44:52 +0000 Subject: [PATCH 069/165] Ensured that onlyIf is applied to anonymous rules (fixes #374) --- Dist/knockout.validation.js | 9 +++++++-- Dist/knockout.validation.min.js | 2 +- Src/api.js | 9 +++++++-- Tests/validation-tests.js | 16 ++++++++++++++++ 4 files changed, 31 insertions(+), 5 deletions(-) diff --git a/Dist/knockout.validation.js b/Dist/knockout.validation.js index 68dd5dfa..5c9c1135 100644 --- a/Dist/knockout.validation.js +++ b/Dist/knockout.validation.js @@ -202,8 +202,8 @@ kv.configuration = configuration; if (obj.__kv_traversed === true) { return; } if (options.deep) { - obj.__kv_traversed = true; - options.flagged.push(obj); + obj.__kv_traversed = true; + options.flagged.push(obj); } //default level value depends on deep option. @@ -391,6 +391,11 @@ kv.configuration = configuration; ruleObj['message'] = 'Error'; } + //make sure onlyIf is honoured + if (ruleObj.onlyIf) { + ruleObj.condition = ruleObj.onlyIf; + } + //add the anonymous rule to the observable kv.addRule(observable, ruleObj); }, diff --git a/Dist/knockout.validation.min.js b/Dist/knockout.validation.min.js index 6b2a96b1..cad0e585 100644 --- a/Dist/knockout.validation.min.js +++ b/Dist/knockout.validation.min.js @@ -5,4 +5,4 @@ Description: Validation Library for KnockoutJS =============================================================================== */ -!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for week input. Should look like '2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for month input. Should look like '2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:h(c.params))?!0:(a.setError(f.formatMessage(c.message||b.message,h(c.params))),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,h(c.params))),a.__valid__(e)),a.isValidating(!1),void 0):(a.isValidating(!1),void 0)};b.validator(a(),h(c.params||!0),d)}if(void 0===typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return!!(a&&a.rules&&a.isValid&&a.isModified)},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},forEach:function(a,b){if(f.utils.isArray(a))return i(a,b);for(var c in a)a.hasOwnProperty(c)&&b(a[c],c)}}}();var m=function(){function b(c,d,e){var f=[],g=h(c);d.flagged||(d.flagged=[]),d.toValidate||(d.toValidate=[]),c.__kv_traversed!==!0&&(d.deep&&(c.__kv_traversed=!0,d.flagged.push(c)),e=void 0!==e?e:d.deep?1:-1,a.isObservable(c)&&(c.isValid||c.extend({validatable:!0}),d.toValidate.push(c)),g&&(k.isArray(g)||k.isObject(g))&&(f=g),0!==e&&k.forEach(f,function(a){a&&!a.nodeType&&b(a,d,e+1)}))}function c(a){var b=[];return i(a,function(a){a.isValid()||b.push(a.error)}),b}var d=0,e=f.configuration,k=f.utils;return{init:function(a,b){d>0&&!b||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||e.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||e.errorMessageClass,j(e,a),e.registerExtenders&&f.registerExtenders(),d=1)},configure:function(a){f.init(a)},reset:f.configuration.reset,group:function(d,f){f=j(j({},e.grouping),f);var h=a.observableArray([]),k=null,l=function(){f.deep&&(i(f.flagged,function(a){delete a.__kv_traversed}),f.flagged.length=0),f.toValidate=[]};return f.observable?(b(d,f),h(f.toValidate),l(),k=a.computed(function(){return c(h())})):k=function(){return b(d,f),h(f.toValidate),l(),c(h())},k.showAllMessages=function(a){void 0===a&&(a=!0),k(),i(h(),function(b){b.isModified(a)})},d.errors=k,d.isValid=function(){return 0===d.errors().length},d.isAnyMessageShown=function(){var a=!1;return k(),a=!!g.arrayFirst(h(),function(a){return!a.isValid()&&a.isModified()})},k},formatMessage:function(a,b){return"function"==typeof a?a(b):a.replace(/\{0\}/gi,h(b))},addRule:function(a,b){return a.extend({validatable:!0}),a.rules.push(b),a},addAnonymousRule:function(a,b){void 0===b.message&&(b.message="Error"),f.addRule(a,b)},addExtender:function(b){a.extenders[b]=function(a,c){return c&&(c.message||c.onlyIf)?f.addRule(a,{rule:b,message:c.message,params:k.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(e.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=k.getConfigOptions(a).errorMessageClass,k.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(k.hasAttribute(a,c)){var d=a.getAttribute(c)||!0;if("min"===c||"max"===c){var e=a.getAttribute("type");"undefined"!=typeof e&&e||(e="text"),d={typeAttr:e,value:d}}f.addRule(b(),{rule:c,params:d})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(a,b){var c=b();if(c&&c.rules){var d=c.rules();i(f.configuration.html5Attributes,function(b){var c,e=g.arrayFirst(d,function(a){return a.rule.toLowerCase()===b.toLowerCase()});e&&(c=e.params,"pattern"===e.rule&&e.params instanceof RegExp&&(c=e.params.source),a.setAttribute(b,c))}),d=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var d=function(b,c){if(b&&c)for(var e in c)if(c.hasOwnProperty(e)){var g=c[e];if(b[e]){var i=b[e],j=h(i),l={},m={};for(var n in g)g.hasOwnProperty(n)&&(f.rules[n]?l[n]=g[n]:m[n]=g[n]);if(a.isObservable(i)&&i.extend(l),j&&k.isArray(j))for(var o=0;o0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){return f.utils.isEmptyVal(a)||a.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){return f.utils.isEmptyVal(a)||a.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}"},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address"},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date"},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(a):!0},message:"Please enter a proper date"},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number"},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit"},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number"},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal"},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(c,function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateInputElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),i=(h(d),!1),j=!1;if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");i=d.isModified(),j=d.isValid();var k=null;(!e.messagesOnModified||i)&&(k=j?null:d.error);var l=!e.messagesOnModified||i?!j:!1,m="none"!==b.style.display;e.allowHtmlMessages?g.setHtml(b,k):a.bindingHandlers.text.update(b,function(){return k}),m&&!l?b.style.display="none":!m&&l&&(b.style.display="")}},a.bindingHandlers.validationElement={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),g=(h(d),!1),i=!1;if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");g=d.isModified(),i=d.isValid();var j=function(){var a={},b=!e.decorateElementOnModified||g?!i:!1;return a[e.errorElementClass]=b,a};a.bindingHandlers.css.update(b,j),e.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!e.errorsAsTitleOnModified||g,c=f.utils.getOriginalElementTitle(b);return a&&!i?{title:d.error,"data-orig-title":c}:!a||i?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){b.error(a),b.__valid__(!1)},b.clearError=function(){return b.error(null),b.__valid__(!0),b};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){b(),b.rules();return f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified.getSubscriptionsCount()>0&&(b.isModified._subscriptions.change=[]),b.isValidating.getSubscriptionsCount()>0&&(b.isValidating._subscriptions.change=[]),b.__valid__.getSubscriptionsCount()>0&&(b.__valid__._subscriptions.change=[]),g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=c.rule?f.rules[c.rule]:c,b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0},f.localize=function(a){var b;for(b in a)f.rules.hasOwnProperty(b)&&(f.rules[b].message=a[b])},a.applyBindingsWithValidation=function(b,c,d){var e,g,h=arguments.length;h>2?(e=c,g=d):2>h?e=document.body:arguments[1].nodeType?e=c:g=arguments[1],f.init(),g&&f.utils.setDomData(e,g),a.applyBindings(b,c)};var n=a.applyBindings;a.applyBindings=function(a,b){f.init(),n(a,b)},a.validatedObservable=function(b){if(!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var c=a.observable(b);return c.isValid=a.observable(),c.errors=f.group(b),c.errors.subscribe(function(a){c.isValid(0===a.length)}),c}}); \ No newline at end of file +!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for week input. Should look like "+"'2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for month input. Should look like "+"'2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:h(c.params))?!0:(a.setError(f.formatMessage(c.message||b.message,h(c.params))),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,h(c.params))),a.__valid__(e)),a.isValidating(!1),void 0):(a.isValidating(!1),void 0)};b.validator(a(),h(c.params||!0),d)}if(void 0===typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return!!(a&&a.rules&&a.isValid&&a.isModified)},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},forEach:function(a,b){if(f.utils.isArray(a))return i(a,b);for(var c in a)a.hasOwnProperty(c)&&b(a[c],c)}}}();var m=function(){function b(c,d,e){var f=[],g=h(c);d.flagged||(d.flagged=[]),d.toValidate||(d.toValidate=[]),c.__kv_traversed!==!0&&(d.deep&&(c.__kv_traversed=!0,d.flagged.push(c)),e=void 0!==e?e:d.deep?1:-1,a.isObservable(c)&&(c.isValid||c.extend({validatable:!0}),d.toValidate.push(c)),g&&(k.isArray(g)||k.isObject(g))&&(f=g),0!==e&&k.forEach(f,function(a){a&&!a.nodeType&&b(a,d,e+1)}))}function c(a){var b=[];return i(a,function(a){a.isValid()||b.push(a.error)}),b}var d=0,e=f.configuration,k=f.utils;return{init:function(a,b){d>0&&!b||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||e.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||e.errorMessageClass,j(e,a),e.registerExtenders&&f.registerExtenders(),d=1)},configure:function(a){f.init(a)},reset:f.configuration.reset,group:function(d,f){f=j(j({},e.grouping),f);var h=a.observableArray([]),k=null,l=function(){f.deep&&(i(f.flagged,function(a){delete a.__kv_traversed}),f.flagged.length=0),f.toValidate=[]};return f.observable?(b(d,f),h(f.toValidate),l(),k=a.computed(function(){return c(h())})):k=function(){return b(d,f),h(f.toValidate),l(),c(h())},k.showAllMessages=function(a){void 0===a&&(a=!0),k(),i(h(),function(b){b.isModified(a)})},d.errors=k,d.isValid=function(){return 0===d.errors().length},d.isAnyMessageShown=function(){var a=!1;return k(),a=!!g.arrayFirst(h(),function(a){return!a.isValid()&&a.isModified()})},k},formatMessage:function(a,b){return"function"==typeof a?a(b):a.replace(/\{0\}/gi,h(b))},addRule:function(a,b){return a.extend({validatable:!0}),a.rules.push(b),a},addAnonymousRule:function(a,b){void 0===b.message&&(b.message="Error"),b.onlyIf&&(b.condition=b.onlyIf),f.addRule(a,b)},addExtender:function(b){a.extenders[b]=function(a,c){return c&&(c.message||c.onlyIf)?f.addRule(a,{rule:b,message:c.message,params:k.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(e.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=k.getConfigOptions(a).errorMessageClass,k.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(k.hasAttribute(a,c)){var d=a.getAttribute(c)||!0;if("min"===c||"max"===c){var e=a.getAttribute("type");"undefined"!=typeof e&&e||(e="text"),d={typeAttr:e,value:d}}f.addRule(b(),{rule:c,params:d})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(a,b){var c=b();if(c&&c.rules){var d=c.rules();i(f.configuration.html5Attributes,function(b){var c,e=g.arrayFirst(d,function(a){return a.rule.toLowerCase()===b.toLowerCase()});e&&(c=e.params,"pattern"===e.rule&&e.params instanceof RegExp&&(c=e.params.source),a.setAttribute(b,c))}),d=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var d=function(b,c){if(b&&c)for(var e in c)if(c.hasOwnProperty(e)){var g=c[e];if(b[e]){var i=b[e],j=h(i),l={},m={};for(var n in g)g.hasOwnProperty(n)&&(f.rules[n]?l[n]=g[n]:m[n]=g[n]);if(a.isObservable(i)&&i.extend(l),j&&k.isArray(j))for(var o=0;o0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){return f.utils.isEmptyVal(a)||a.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){return f.utils.isEmptyVal(a)||a.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}"},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address"},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date"},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(a):!0},message:"Please enter a proper date"},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number"},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit"},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number"},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal"},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(c,function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateInputElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),i=(h(d),!1),j=!1;if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");i=d.isModified(),j=d.isValid();var k=null;(!e.messagesOnModified||i)&&(k=j?null:d.error);var l=!e.messagesOnModified||i?!j:!1,m="none"!==b.style.display;e.allowHtmlMessages?g.setHtml(b,k):a.bindingHandlers.text.update(b,function(){return k}),m&&!l?b.style.display="none":!m&&l&&(b.style.display="")}},a.bindingHandlers.validationElement={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),g=(h(d),!1),i=!1;if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");g=d.isModified(),i=d.isValid();var j=function(){var a={},b=!e.decorateElementOnModified||g?!i:!1;return a[e.errorElementClass]=b,a};a.bindingHandlers.css.update(b,j),e.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!e.errorsAsTitleOnModified||g,c=f.utils.getOriginalElementTitle(b);return a&&!i?{title:d.error,"data-orig-title":c}:!a||i?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){b.error(a),b.__valid__(!1)},b.clearError=function(){return b.error(null),b.__valid__(!0),b};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){return b(),b.rules(),f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified.getSubscriptionsCount()>0&&(b.isModified._subscriptions.change=[]),b.isValidating.getSubscriptionsCount()>0&&(b.isValidating._subscriptions.change=[]),b.__valid__.getSubscriptionsCount()>0&&(b.__valid__._subscriptions.change=[]),g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=c.rule?f.rules[c.rule]:c,b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0},f.localize=function(a){var b;for(b in a)f.rules.hasOwnProperty(b)&&(f.rules[b].message=a[b])},a.applyBindingsWithValidation=function(b,c,d){var e,g,h=arguments.length;h>2?(e=c,g=d):2>h?e=document.body:arguments[1].nodeType?e=c:g=arguments[1],f.init(),g&&f.utils.setDomData(e,g),a.applyBindings(b,c)};var n=a.applyBindings;a.applyBindings=function(a,b){f.init(),n(a,b)},a.validatedObservable=function(b){if(!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var c=a.observable(b);return c.isValid=a.observable(),c.errors=f.group(b),c.errors.subscribe(function(a){c.isValid(0===a.length)}),c}}); \ No newline at end of file diff --git a/Src/api.js b/Src/api.js index 84814f30..cb5d7a5b 100644 --- a/Src/api.js +++ b/Src/api.js @@ -20,8 +20,8 @@ if (obj.__kv_traversed === true) { return; } if (options.deep) { - obj.__kv_traversed = true; - options.flagged.push(obj); + obj.__kv_traversed = true; + options.flagged.push(obj); } //default level value depends on deep option. @@ -209,6 +209,11 @@ ruleObj['message'] = 'Error'; } + //make sure onlyIf is honoured + if (ruleObj.onlyIf) { + ruleObj.condition = ruleObj.onlyIf; + } + //add the anonymous rule to the observable ko.validation.addRule(observable, ruleObj); }, diff --git a/Tests/validation-tests.js b/Tests/validation-tests.js index 7d00b356..3cb8257d 100644 --- a/Tests/validation-tests.js +++ b/Tests/validation-tests.js @@ -1346,6 +1346,22 @@ test('Issue #78 - Falsy Params', function () { equal(testObj.isValid(), false, 'testObj is not valid'); }); + +test("Issue 374 - onlyIf ignored", function () { + var observable = ko.observable(), + validationEnabled = ko.observable(true); + observable.extend({ + validation: { + validator: function () { return false; }, //always fail validation + onlyIf: validationEnabled + } + }); + + ok(!observable.isValid(), "Should be validating as onlyIf returns true"); + validationEnabled(false); + ok(observable.isValid(), "Validation should now be disabled"); +}); + //#endregion //#region Manual Validation From 6e145f28ec20bb52556adb00081fc6b71041cbe1 Mon Sep 17 00:00:00 2001 From: bogatykh Date: Wed, 11 Dec 2013 11:10:07 +0200 Subject: [PATCH 070/165] Latvian (lv-LV) localization added --- Localization/lv-LV.js | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Localization/lv-LV.js diff --git a/Localization/lv-LV.js b/Localization/lv-LV.js new file mode 100644 index 00000000..50dcf118 --- /dev/null +++ b/Localization/lv-LV.js @@ -0,0 +1,39 @@ +/// + +/************************************************ +* This is an example localization page. All of these +* messages are the default messages for ko.validation +* +* Currently ko.validation only does a single parameter replacement +* on your message (indicated by the {0}). +* +* The parameter that you provide in your validation extender +* is what is passed to your message to do the {0} replacement. +* +* eg: myProperty.extend({ minLength: 5 }); +* ... will provide a message of "Please enter at least 5 characters" +* when validated +* +* This message replacement obviously only works with primitives +* such as numbers and strings. We do not stringify complex objects +* or anything like that currently. +*/ + +ko.validation.localize({ + required: 'Lauks ir obligāts.', + min: 'Lūdzu, ievadiet vērtību lielāku vai vienādu ar {0}.', + max: 'Lūdzu, ievadiet vērtību mazāku vai vienādu par {0}.', + minLength: 'Lūdzu, ievadiet vismaz {0} simbolus.', + maxLength: 'Lūdzu, ievadiet ne vairāk kā {0} simbolus.', + pattern: 'Lūdzu, pārbaudiet norādītās vērtības formātu.', + step: 'Norādītām vērtībām jābūt pieaugošām ar soli {0}', + email: 'Norādītā e-pasta adrese neatbilst formātam', + date: 'Lūdzu, norādiet atbilstošu datuma formātu.', + dateISO: 'Lūdzu, norādiet atbilstošu datuma formātu.', + number: 'Lūdzu, ievadiet numuru.', + digit: 'Lūdzu, ievadiet ciparu.', + phoneUS: 'Lūdzu, norādiet formātam atbilstošu telefona numuru.', + equal: 'Norādītām vērtībām jābūt vienādām.', + notEqual: 'Norādītās vērtības nav vienādas.', + unique: 'Vērtībai jābūt unikālai.' +}); From 7042c5f268ef7ab650f0811004b5f36b3d2e574a Mon Sep 17 00:00:00 2001 From: Steve Greatrex Date: Thu, 12 Dec 2013 18:49:56 +0000 Subject: [PATCH 071/165] Split tests out into multiple files (fixes #375) --- Tests/api-tests.js | 469 ++++++++ Tests/rules-tests.js | 1137 +++++++++++++++++++ Tests/test-runner.htm | 3 + Tests/utils-tests.js | 175 +++ Tests/validation-tests.js | 2167 ++++--------------------------------- 5 files changed, 2002 insertions(+), 1949 deletions(-) create mode 100644 Tests/api-tests.js create mode 100644 Tests/rules-tests.js create mode 100644 Tests/utils-tests.js diff --git a/Tests/api-tests.js b/Tests/api-tests.js new file mode 100644 index 00000000..850efae8 --- /dev/null +++ b/Tests/api-tests.js @@ -0,0 +1,469 @@ +/*global + module:false, + equal:false, + notEqual:false, + strictEqual:false, + deepEqual:false, + test:false, + ok:false, + asyncTest:false, + start: false, + stop: false, + expect: false +*/ + +//#region Manual Validation +module("Manual Validation"); +test("setError sets isValid and error message", function () { + var testObj = ko.observable(); + testObj.extend({ validatable: true }); + + //check initial validation state + ok(testObj.isValid()); + equal(testObj.error(), null); + + //manually set an error + testObj.setError("oh no!"); + + //check state was set + ok(!testObj.isValid()); + equal("oh no!", testObj.error()); +}); + +test("clearError clears manually-specified error", function () { + var testObj = ko.observable(); + testObj.extend({ validatable: true }); + testObj.setError("oh no!"); + + //fail the validation + ok(!testObj.isValid()); + + //clear the validation + var result = testObj.clearError(); + equal(testObj, result, "The result should be returned to support chaining"); + + //check state was cleared + ok(testObj.isValid()); + equal(testObj.error(), null); +}); + +test("clearError clears automatic errors", function () { + var testObj = ko.observable(5); + testObj.extend({ min: 6 }); + + //check initial state + ok(!testObj.isValid()); + + var result = testObj.clearError(); + equal(testObj, result, "The result should be returned to support chaining"); + + //check validation was cleared + ok(testObj.isValid()); + equal(testObj.error(), null); +}); + +//#endregion + +//#region Grouping Tests +module('Grouping Tests'); + +test('Error Grouping works', function () { + var vm = { + firstName: ko.observable().extend({ required: true }), + lastName: ko.observable().extend({ required: 2 }) + }; + + var errors = ko.validation.group(vm); + + equal(errors().length, 2, 'Grouping correctly finds 2 invalid properties'); +}); + +test('Nested Grouping works - Observable', function () { + var vm = { + one: ko.observable().extend({ required: true }), + two: { + one: ko.observable().extend({ required: true }) + }, + three: { + two: { + one: ko.observable().extend({ required: true }) + } + } + }; + + var errors = ko.validation.group(vm, { deep: true, observable: true }); + + equal(errors().length, 3, 'Grouping correctly finds 3 invalid properties'); +}); + +test('Nested Grouping works - Not Observable', function () { + var vm = { + one: ko.observable().extend({ required: true }), + two: { + one: ko.observable().extend({ required: true }) + }, + three: { + two: { + one: ko.observable().extend({ required: true }) + } + } + }; + + var errors = ko.validation.group(vm, { deep: true, observable: false }); + + equal(errors().length, 3, 'Grouping correctly finds 3 invalid properties'); +}); + +test('Nested grouping finds items in observableArrays - observable', function () { + var vm = { array: ko.observableArray([{ one: ko.observable().extend({ required: true }) }]) }; + + var errors = ko.validation.group(vm, { deep: true, observable: true }); + + equal(errors().length, 1, 'Grouping finds property on object in observableArray'); +}); + +test('Nested grouping does not add items newly inserted into observableArrays to result - observable, not live', function () { + var vm = { array: ko.observableArray() }; + + var errors = ko.validation.group(vm, { deep: true, observable: true, live: false }); + + vm.array.push({ one: ko.observable().extend({ required: true }) }); + + equal(errors().length, 0, 'grouping does not add newly items newly inserted into observableArrays to result'); +}); + +test('Nested grouping adds items newly inserted into an observableArrays nested in an object in an observableArray to result - observable, live', function () { + var vm = { array: ko.observableArray() }; + + var errors = ko.validation.group(vm, { deep: true, observable: true, live: true }); + + vm.array.push({ array: ko.observableArray() }); + vm.array()[0].array.push({ one: ko.observable().extend({ required: true }) }); + + equal(errors().length, 1, 'grouping adds newly items newly inserted into observableArrays to result'); +}); + +test('Nested grouping adds items newly inserted into observableArrays to result - observable, live', function () { + var vm = { array: ko.observableArray() }; + + var errors = ko.validation.group(vm, { deep: true, observable: true, live: true }); + + vm.array.push({ one: ko.observable().extend({ required: true }) }); + + equal(errors().length, 1, 'grouping adds newly items newly inserted into observableArrays to result'); +}); + +test('Nested grouping ignores items nested in destroyed objects - not observable', function () { + var obj = { nested: ko.observable().extend({ required: true }) }; + + function getErrorCount() { + return ko.validation.group(obj, { deep: true, observable: false, live: false })().length; + } + + equal(getErrorCount(), 1, 'obj is not destroyed and should return nested\'s error'); + + obj._destroy = true; + + equal(getErrorCount(), 0, 'obj is destroyed and nested therefore ignored'); +}); + +test('Nested grouping ignores items nested in destroyed objects - observable, live', function () { + var obj = { nested: ko.observable().extend({ required: true }) }; + var array = ko.observableArray([obj]); + var vm = { array: array }; + + var errors = ko.validation.group(vm, { deep: true, observable: true, live: true }); + + equal(errors().length, 1, 'obj is not yet destroyed and nested therefore invalid'); + array.destroy(obj); + equal(errors().length, 0, 'obj is destroyed and nested therefore ignored'); +}); + +test('Nested grouping does not cause the reevaluation of computeds depending on the result for every observable', function () { + var vm = { array: ko.observableArray() }; + + var errors = ko.validation.group(vm, { deep: true, observable: true, live: true }); + + var computedHitCount = 0; + var computed = ko.computed(function () { + computedHitCount++; + errors(); + }); + + vm.array.push({ one: ko.observable().extend({ required: true }) }); + equal(computedHitCount, 2, 'first one while creating the computed, second one for adding the item'); + + vm.array.push({ one: ko.observable().extend({ required: true }) }); + equal(computedHitCount, 3, 'Only one additional re-evaluation should have been triggered'); + + vm.array.push({ one: ko.observable().extend({ required: true }) }); + equal(computedHitCount, 4, 'Only one additional re-evaluation should have been triggered'); + +}); + +test('Nested grouping adds items newly inserted into observableArrays to result - cleares validatables before traversing again - observable, live', function () { + var vm = { array: ko.observableArray() }; + + var errors = ko.validation.group(vm, { deep: true, observable: true, live: true }); + + vm.array.push({ one: ko.observable().extend({ required: true }) }); + vm.array.push({ one: ko.observable().extend({ required: true }) }); + + equal(errors().length, 2, 'validatables are added only once'); +}); + +//#endregion + +//#region validatedObservable +module('validatedObservable Tests'); +test('validatedObservable is Valid', function () { + + var obj = ko.validatedObservable({ + testObj: ko.observable('').extend({ minLength: 5 }), + testObj2: ko.observable('').extend({ required: true }) + }); + + obj().testObj('something'); + obj().testObj2('eric'); + + ok(obj(), 'observable works'); + ok(obj.isValid(), 'observable is valid'); + +}); + +test('validatedObservable is not Valid', function () { + + var obj = ko.validatedObservable({ + testObj: ko.observable('').extend({ minLength: 5 }), + testObj2: ko.observable('').extend({ required: true }) + }); + + obj().testObj('some');// not length of 5 + obj().testObj2('eric'); + + ok(obj(), 'observable works'); + ok(!obj.isValid(), obj.errors()[0]); + +}); + +test('validatedObservable is first Valid then made InValid', function () { + + var obj = ko.validatedObservable({ + testObj: ko.observable('').extend({ minLength: 5 }), + testObj2: ko.observable('').extend({ required: true }) + }); + + //make it valid + obj().testObj('something'); + obj().testObj2('eric'); + + //now make it invalid + obj().testObj('some'); + + ok(obj(), 'observable works'); + ok(!obj.isValid(), obj.errors()[0]); + +}); + +test('validatedObservable does not show error message when not modified', function () { + var obj = ko.validatedObservable({ + testObj: ko.observable('a').extend({ minLength: 5 }), + testObj2: ko.observable('').extend({ required: true }) + }); + + ok(obj(), 'observable works'); + ok(!obj().isAnyMessageShown(), 'validation error message is hidden'); + +}); + + +test('validatedObservable does not show error message when modified but correct', function () { + var obj = ko.validatedObservable({ + testObj: ko.observable('a').extend({ minLength: 5 }), + testObj2: ko.observable('').extend({ required: true }) + }); + + obj().testObj('12345'); + obj().testObj2('a'); + + ok(obj(), 'observable works'); + ok(!obj().isAnyMessageShown(), 'validation error message is hidden'); + +}); + +test('validatedObservable show error message when at least one invalid and modified', function () { + var obj = ko.validatedObservable({ + testObj: ko.observable('a').extend({ minLength: 5 }), + testObj2: ko.observable('').extend({ required: true }) + }); + + obj().testObj.isModified(true); + + ok(obj(), 'observable works'); + ok(obj().isAnyMessageShown(), 'validation error message is shown'); + +}); + +//#endregion + +//#region setRules Tests +module("setRules Tests"); + +test("setRules applies rules to all properties", function () { + var definition = { + property1: { + required: true, + min: 10, + max: 99, + ignoredDefinition: { required: true } + }, + child: { + property2: { + pattern: { + params: "^[a-z0-9].$", + message: "Only AlphaNumeric please" + } + }, + grandchild: { + property3: { + number: true + } + }, + ignoredDefinition: { required: true } + }, + nestedArray: { + property4: { email: true }, + ignoredDefinition: { required: true } + } + }; + + var target = { + property1: ko.observable(), + ignoredProperty: ko.observable(), + child: { + property2: ko.observable(), + ignoredProperty: ko.observable(), + grandchild: { + property3: ko.observable(), + ignoredProperty: ko.observable(), + } + }, + nestedArray: ko.observableArray([ + { property4: ko.observable(), ignoredProperty: ko.observable() }, + { property4: ko.observable(), ignoredProperty: ko.observable() }, + { property4: ko.observable(), ignoredProperty: ko.observable() } + ]) + }; + + ko.validation.setRules(target, definition); + + //check that all rules have been applied + deepEqual(target.property1.rules(), [ + { rule: "required", params: true }, + { rule: "min", params: 10 }, + { rule: "max", params: 99 } + ]); + + deepEqual(target.child.property2.rules(), [ + { rule: "pattern", message: "Only AlphaNumeric please", params: "^[a-z0-9].$", condition: undefined } + ]); + + deepEqual(target.child.grandchild.property3.rules(), [ + { rule: "number", params: true } + ]); + + for (var i = 0; i < target.nestedArray.length; i) { + deepEqual(target.nestedArray[i].property3.rules(), [ + { rule: "email", params: true } + ]); + } + + //check that ignored properties have not had rules added + ok(!target.ignoredProperty.rules); + ok(!target.child.ignoredProperty.rules); + ok(!target.child.grandchild.ignoredProperty.rules); + ok(!target.nestedArray()[0].ignoredProperty.rules); + ok(!target.nestedArray()[1].ignoredProperty.rules); + ok(!target.nestedArray()[2].ignoredProperty.rules); +}); + +//#endregion + +//#region Removing Validation +module('Removing Validation Tests'); + +test('Basic Removal', function () { + var testObj = ko.observable('') + .extend({ min: 2 }); + + testObj(3); + + var testFlag = false; + + equal(testObj(), 3, 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); + + testObj.isValid.subscribe(function () { + testFlag = true; + }); + + testObj.extend({ validatable: false }); + + ok(!testObj.isValid, 'Validation features removed'); + testObj(1); + ok(!testFlag, 'Subscriptions to isValid didnt fire'); + +}); +//#endregion + +//#region validation process tests +module("Validation process", { + setup: function () { + var isStarted = false; + ko.validation._validateObservable = ko.validation.validateObservable; + ko.validation.validateObservable = function () { + ok(true, "Triggered only once"); + if (!isStarted) { + isStarted = true; + start(); + } + + return ko.validation._validateObservable.apply(this, arguments); + }; + }, + + teardown: function () { + ko.validation.validateObservable = ko.validation._validateObservable; + } +}); + +asyncTest("can be throttled using global configuration", function () { + expect(2); // one for initialization and when value changed + + ko.validation.init({ + validate: { + throttle: 10 + } + }, true); + + var observable = ko.observable().extend({ validatable: true }); + observable("1"); + observable.extend({ minLength: 2 }); + + ko.validation.init({ validate: {} }, true); +}); + +asyncTest("can be throttled using using local configuration", function () { + expect(2); // one for initialization and when value changed + + var observable = ko.observable().extend({ + validatable: { + throttle: 10 + } + }); + + observable.extend({ minLength: 2 }); + observable("1"); +}); + +//#endregion \ No newline at end of file diff --git a/Tests/rules-tests.js b/Tests/rules-tests.js new file mode 100644 index 00000000..366e5397 --- /dev/null +++ b/Tests/rules-tests.js @@ -0,0 +1,1137 @@ +/*global + module:false, + equal:false, + notEqual:false, + strictEqual:false, + deepEqual:false, + test:false, + ok:false, + asyncTest:false, + start: false, + stop: false, + expect: false +*/ + +//#region Required Validation + +module('Required Validation'); + +test('Object is Valid and isValid returns True', function () { + + var testObj = ko.observable('') + .extend({ required: true }); + + testObj('something'); + + equal(testObj(), 'something', 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is NOT Valid and isValid returns False', function () { + + var testObj = ko.observable('') + .extend({ required: true }); + + equal(testObj(), '', 'observable still works'); + equal(testObj.isValid(), false, 'testObj is not valid'); +}); + +test('Zero is a valid value for required', function () { + + var testObj = ko.observable(0) + .extend({ required: true }); + + equal(testObj(), 0, 'observable still works'); + equal(testObj.isValid(), true, 'testObj is valid'); +}); + +test('Empty spaces is not a valid value for required', function () { + + var testObj = ko.observable(' ') + .extend({ required: true }); + + equal(testObj(), ' ', 'observable still works'); + equal(testObj.isValid(), false, 'testObj is valid'); +}); + +test('Issue #90 - "required: false" doesnt force validation', function () { + + var testObj = ko.observable() + .extend({ required: false }); + + equal(testObj.isValid(), true, 'testObj is valid without value'); + + testObj('blah'); + equal(testObj.isValid(), true, 'testObj is valid with value'); + + testObj(null); + equal(testObj.isValid(), true, 'testObj is valid without value after set/unset'); +}); + +test("Undefined params should not cause errors", function () { + var undefinedParams = ko.observable().extend({ required: undefined }), + nullParams = ko.observable().extend({ required: null }); + + ok(true, "No errors whilst adding rules? Awesome"); +}); + +test("Issue #376 - empty string should pass validation when required = false", function () { + var observable = ko.observable("").extend({ required: false }); + + ok(observable.isValid(), "Empty string should be vvalid"); +}); + +//#endregion + +//#region Min Validation + +module('Min Validation'); + +test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ min: 2 }); + testObj(); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when null value is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ min: 2 }); + testObj(null); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when empty string is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ min: 2 }); + testObj(''); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid and isValid returns True', function () { + var testObj = ko.observable('') + .extend({ min: 2 }); + + testObj(3); + + equal(testObj(), 3, 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid and isValid returns True (with min: 0)', function () { + var testObj = ko.observable('') + .extend({ min: 0 }); + + testObj("0"); + + equal(testObj(), "0", 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is NOT Valid and isValid returns False', function () { + var testObj = ko.observable('') + .extend({ min: 2 }); + + testObj(1); + + equal(testObj(), 1, 'observable still works'); + equal(testObj.isValid(), false, 'testObj is not valid'); +}); + +test('Object is NOT Valid and isValid returns False and min is observable', function () { + var minValue = ko.observable(3); + var testObj = ko.observable('') + .extend({ min: minValue }); + + testObj(1); + + equal(testObj(), 1, 'observable still works'); + equal(testObj.isValid(), false, 'testObj is not valid'); +}); + +test('Object is Valid and isValid returns True and min is observable', function () { + var minValue = ko.observable(3); + var testObj = ko.observable('') + .extend({ min: minValue }); + + testObj(4); + + equal(testObj(), 4, 'observable still works'); + equal(testObj.isValid(), true, 'testObj is valid'); +}); +//#endregion + +//#region Max Validation + +module('Max Validation'); + +test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ max: 2 }); + testObj(); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when null value is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ max: 2 }); + testObj(null); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when empty string is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ max: 2 }); + testObj(''); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid and isValid returns True', function () { + var testObj = ko.observable('') + .extend({ max: 5 }); + + testObj(3); + + equal(testObj(), 3, 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is NOT Valid and isValid returns False', function () { + var testObj = ko.observable('') + .extend({ max: 5 }); + + testObj(6); + + equal(testObj(), 6, 'observable still works'); + equal(testObj.isValid(), false, 'testObj is not valid'); +}); + +test('Object is NOT Valid and isValid returns False and max is observable', function () { + var minValue = ko.observable(3); + var testObj = ko.observable('') + .extend({ max: minValue }); + + testObj(4); + + equal(testObj(), 4, 'observable still works'); + equal(testObj.isValid(), false, 'testObj is not valid'); +}); + +test('Object is Valid and isValid returns True and max is observable', function () { + var minValue = ko.observable(3); + var testObj = ko.observable('') + .extend({ max: minValue }); + + testObj(1); + + equal(testObj(), 1, 'observable still works'); + equal(testObj.isValid(), true, 'testObj is valid'); +}); +//#endregion + +//#region Min Length Validation + +module('MinLength Validation'); + +test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ minLength: 2 }); + testObj(); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when null value is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ minLength: 2 }); + testObj(null); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when empty string is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ minLength: 2 }); + testObj(''); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when no value is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ minLength: 2 }); + testObj(''); + ok(testObj.isValid(), 'testObj is Valid'); + +}); + +test('Object is Valid and isValid returns True', function () { + var testObj = ko.observable('') + .extend({ minLength: 5 }); + + testObj('something'); + + equal(testObj(), 'something', 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is NOT Valid and isValid returns False', function () { + var testObj = ko.observable('') + .extend({ minLength: 12 }); + + testObj('something'); + + equal(testObj(), 'something', 'observable still works'); + equal(testObj.isValid(), false, 'testObj is not valid'); +}); + +test('Issue #33 - Arrays - Valid', function () { + var testObj = ko.observableArray() + .extend({ minLength: 2 }); + + testObj(['one', 'two', 'three']); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Issue #33 - Arrays - Invalid', function () { + var testObj = ko.observableArray() + .extend({ minLength: 4 }); + + testObj(['one', 'two', 'three']); + ok(!testObj.isValid(), testObj.error()); +}); + +test('Object is Valid and minLength is observable and isValid returns True', function () { + var minLength = ko.observable(5); + var testObj = ko.observable('') + .extend({ minLength: minLength }); + + testObj('something'); + + equal(testObj(), 'something', 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is NOT Valid and minLength is observable and isValid returns False', function () { + var minLength = ko.observable(12); + var testObj = ko.observable('') + .extend({ minLength: minLength }); + + testObj('something'); + + equal(testObj(), 'something', 'observable still works'); + equal(testObj.isValid(), false, 'testObj is not valid'); +}); +//#endregion + +//#region Max Length Validation + +module('MaxLength Validation'); + +test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ maxLength: 2 }); + testObj(); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when null value is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ maxLength: 2 }); + testObj(null); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when empty string is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ maxLength: 2 }); + testObj(''); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid and isValid returns True', function () { + var testObj = ko.observable('') + .extend({ maxLength: 10 }); + + testObj('something'); + + equal(testObj(), 'something', 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is NOT Valid and isValid returns False', function () { + var testObj = ko.observable('') + .extend({ maxLength: 6 }); + + testObj('something'); + + equal(testObj(), 'something', 'observable still works'); + equal(testObj.isValid(), false, 'testObj is not valid'); +}); + +test('Issue #33 - Arrays - Valid', function () { + var testObj = ko.observableArray() + .extend({ maxLength: 4 }); + + testObj(['one', 'two', 'three']); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Issue #33 - Arrays - Invalid', function () { + var testObj = ko.observableArray() + .extend({ maxLength: 2 }); + + testObj(['one', 'two', 'three']); + ok(!testObj.isValid(), testObj.error()); +}); + +test('Object is Valid and maxLength is observable and isValid returns True', function () { + var maxLength = ko.observable(20); + var testObj = ko.observable('') + .extend({ maxLength: maxLength }); + + testObj('something'); + + equal(testObj(), 'something', 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is NOT Valid and maxLength is observable and isValid returns False', function () { + var maxLength = ko.observable(3); + var testObj = ko.observable('') + .extend({ maxLength: maxLength }); + + testObj('something'); + + equal(testObj(), 'something', 'observable still works'); + equal(testObj.isValid(), false, 'testObj is not valid'); +}); + +//#endregion + +//#region Pattern Validation + +module('Pattern Validation'); + +test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ pattern: 'test' }); + testObj(); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when null value is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ pattern: 'test' }); + testObj(null); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when empty string is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ pattern: 'test' }); + testObj(''); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid and isValid returns True', function () { + var testObj = ko.observable('') + .extend({ pattern: 'some' }); + + testObj('something'); + + equal(testObj(), 'something', 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is NOT Valid and isValid returns False', function () { + var testObj = ko.observable('') + .extend({ pattern: 'none' }); + + testObj('something'); + + equal(testObj(), 'something', 'observable still works'); + equal(testObj.isValid(), false, 'testObj is not valid'); +}); + +test('Pattern validation matches numbers', function () { + var testObj = ko.observable('') + .extend({ pattern: '^12' }); + + testObj(123); + + equal(testObj(), 123, 'observable still works'); + equal(testObj.isValid(), true, 'testObj is valid'); +}); + +test('Pattern validation mismatches numbers', function () { + var testObj = ko.observable('') + .extend({ pattern: 'none' }); + + testObj(123); + + equal(testObj(), 123, 'observable still works'); + equal(testObj.isValid(), false, 'testObj is not valid'); +}); + +test('Pattern validation doesn\'t break with non-string values', function () { + var testObj = ko.observable('') + .extend({ pattern: '^$' }); + + testObj(12345); + testObj.isValid(); + + testObj(12.34); + testObj.isValid(); + + testObj(true); + testObj.isValid(); + + testObj(false); + testObj.isValid(); + + testObj([]); + testObj.isValid(); + + testObj({}); + testObj.isValid(); + + expect(0); +}); + +test('Pattern validation matches numbers and pattern is observable', function () { + var pattern = ko.observable('^12'); + var testObj = ko.observable('') + .extend({ pattern: pattern }); + + testObj(123); + + equal(testObj(), 123, 'observable still works'); + equal(testObj.isValid(), true, 'testObj is valid'); +}); + +test('Pattern validation mismatches numbers and pattern is observable', function () { + var pattern = ko.observable('none'); + var testObj = ko.observable('') + .extend({ pattern: 'none' }); + + testObj(123); + + equal(testObj(), 123, 'observable still works'); + equal(testObj.isValid(), false, 'testObj is not valid'); +}); +//#endregion + +//#region Step Validation + +module('Step Validation'); + +test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ step: 2 }); + testObj(); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when null value is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ step: 2 }); + testObj(null); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when empty string is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ step: 2 }); + testObj(''); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid and isValid returns True', function () { + var testObj = ko.observable('') + .extend({ step: 3 }); + + testObj(6); + + equal(testObj(), 6, 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is NOT Valid and isValid returns False', function () { + var testObj = ko.observable('') + .extend({ step: 2 }); + + testObj(5); + + equal(testObj(), 5, 'observable still works'); + equal(testObj.isValid(), false, 'testObj is not valid'); +}); + +test('Issue 74 - Object is Valid with a step of 0.1 and isValid returns True', function () { + var testObj = ko.observable('') + .extend({ step: 0.1 }); + + testObj(6); + + equal(testObj(), 6, 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + + +test('Issue 74 - Object is Valid with a step of 0.1 and incremented by 0.1 and isValid returns True', function () { + var testObj = ko.observable(6) + .extend({ step: 0.1 }); + + testObj(6.1); + + equal(testObj(), 6.1, 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Issue 74 - Object is NOT Valid with a step of 0.1 and isValid returns False', function () { + var testObj = ko.observable('') + .extend({ step: 0.1 }); + + testObj(5); + testObj(5.15); + + equal(testObj(), 5.15, 'observable still works'); + equal(testObj.isValid(), false, 'testObj is not valid'); +}); + +test('Step validation fix regression check', function () { + var testObj = ko.observable(33.34).extend({ step: 0.01 }); + ok(!testObj.error(), 'step validation not triggered'); +}); + +test('Step validation any value is allowed', function () { + var testObj = ko.observable(33.34).extend({ step: 'any' }); + ok(!testObj.error(), '"any" value for step is allowed'); +}); + +test('Object is Valid and step is observable and isValid returns True', function () { + var step = ko.observable(3); + var testObj = ko.observable('') + .extend({ step: step }); + + testObj(6); + + equal(testObj(), 6, 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is NOT Valid and step is observable and isValid returns False', function () { + var step = ko.observable(3); + var testObj = ko.observable('') + .extend({ step: step }); + + testObj(5); + + equal(testObj(), 5, 'observable still works'); + equal(testObj.isValid(), false, 'testObj is not valid'); +}); + +//#endregion + +//#region Email Validation + +module('Email Validation'); + +test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ email: true }); + testObj(); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when null value is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ email: true }); + testObj(null); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when empty string is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ email: true }); + testObj(''); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid and isValid returns True', function () { + var testObj = ko.observable('').extend({ email: true }); + + testObj('test@example.com'); + + equal(testObj(), 'test@example.com', 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is NOT Valid and isValid returns False', function () { + var testObj = ko.observable('').extend({ email: true }); + + testObj('text#example.com'); + + equal(testObj(), 'text#example.com', 'observable still works'); + equal(testObj.isValid(), false, testObj.error()); + equal(testObj.error(), 'Please enter a proper email address', "Error Message Needs to be formatted correctly"); +}); + +test('Email with invalid domain', function () { + var testObj = ko.observable().extend({ email: true }); + + testObj("john@abc.com123"); + + equal(testObj.isValid(), false, testObj.error()); + equal(testObj.error(), 'Please enter a proper email address'); +}); + +test('Object is Valid and email is observable and isValid returns True', function () { + var email = ko.observable(true); + var testObj = ko.observable('').extend({ email: email }); + + testObj('test@example.com'); + + equal(testObj(), 'test@example.com', 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is NOT Valid and email is observable and isValid returns False', function () { + var email = ko.observable(true); + var testObj = ko.observable('').extend({ email: email }); + + testObj('text#example.com'); + + equal(testObj(), 'text#example.com', 'observable still works'); + equal(testObj.isValid(), false, testObj.error()); + equal(testObj.error(), 'Please enter a proper email address', "Error Message Needs to be formatted correctly"); +}); +//#endregion + +//#region Date Validation + +module('Date Validation'); + +test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ date: 'test' }); + testObj(); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when null value is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ date: 'test' }); + testObj(null); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when empty string is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ date: 'test' }); + testObj(''); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid and isValid returns True', function () { + var testObj = ko.observable('').extend({ date: true }); + + testObj('11/18/2011'); + + equal(testObj(), '11/18/2011', 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is NOT Valid and isValid returns False', function () { + var testObj = ko.observable('').extend({ date: true }); + + testObj('stuff'); + + equal(testObj(), 'stuff', 'observable still works'); + equal(testObj.isValid(), false, testObj.error()); +}); + +test('Object is Valid and date is observable and isValid returns True', function () { + var date = ko.observable(true); + var testObj = ko.observable('').extend({ date: date }); + + testObj('11/18/2011'); + + equal(testObj(), '11/18/2011', 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is NOT Valid and isValid returns False', function () { + var date = ko.observable(true); + var testObj = ko.observable('').extend({ date: date }); + + testObj('stuff'); + + equal(testObj(), 'stuff', 'observable still works'); + equal(testObj.isValid(), false, testObj.error()); +}); + +//#endregion + +//#region DateISO Validation + +module('DateISO Validation'); + +test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ dateISO: 'test' }); + testObj(); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when null value is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ dateISO: 'test' }); + testObj(null); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when empty string is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ dateISO: 'test' }); + testObj(''); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid and isValid returns True', function () { + var testObj = ko.observable('').extend({ dateISO: true }); + + testObj('2011-11-18'); + + equal(testObj(), '2011-11-18', 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is NOT Valid and isValid returns False', function () { + var testObj = ko.observable('').extend({ dateISO: true }); + + testObj('stuff'); + + equal(testObj(), 'stuff', 'observable still works'); + equal(testObj.isValid(), false, testObj.error()); +}); + +test('Object is Valid and dateISO is observable and isValid returns True', function () { + var dateISO = ko.observable(true); + var testObj = ko.observable('').extend({ dateISO: dateISO }); + + testObj('2011-11-18'); + + equal(testObj(), '2011-11-18', 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is NOT Valid and dateISO is observable and isValid returns False', function () { + var dateISO = ko.observable(true); + var testObj = ko.observable('').extend({ dateISO: dateISO }); + + testObj('stuff'); + + equal(testObj(), 'stuff', 'observable still works'); + equal(testObj.isValid(), false, testObj.error()); +}); + +//#endregion + +//#region Number Validation + +module('Number Validation'); + +test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ number: true }); + testObj(); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when null value is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ number: true }); + testObj(null); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when empty string is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ number: true }); + testObj(''); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid and isValid returns True', function () { + var testObj = ko.observable('').extend({ number: true }); + + testObj(200.01); + + equal(testObj(), 200.01, 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Number is Valid (starting with point) and isValid returns True', function () { + var testObj = ko.observable('').extend({ number: true }); + + testObj(".15"); + + equal(testObj(), ".15", 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is NOT Valid and isValid returns False', function () { + var testObj = ko.observable('').extend({ number: true }); + + testObj('stuff'); + + equal(testObj(), 'stuff', 'observable still works'); + equal(testObj.isValid(), false, testObj.error()); +}); + +test('Number is Valid (starting with point) and number is observable and isValid returns True', function () { + var number = ko.observable(true); + var testObj = ko.observable('').extend({ number: number }); + + testObj(".15"); + + equal(testObj(), ".15", 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is NOT Valid and number is observable and isValid returns False', function () { + var number = ko.observable(true); + var testObj = ko.observable('').extend({ number: number }); + + testObj('stuff'); + + equal(testObj(), 'stuff', 'observable still works'); + equal(testObj.isValid(), false, testObj.error()); +}); +//#endregion + +//#region Digit Validation + +module('Digit Validation'); + +test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ digit: true }); + testObj(); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when null value is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ digit: true }); + testObj(null); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when empty string is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ digit: true }); + testObj(''); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid and isValid returns True', function () { + var testObj = ko.observable('').extend({ digit: true }); + + testObj(2); + + equal(testObj(), 2, 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is NOT Valid and isValid returns False', function () { + var testObj = ko.observable('').extend({ digit: true }); + + testObj('stuff'); + + equal(testObj(), 'stuff', 'observable still works'); + equal(testObj.isValid(), false, testObj.error()); +}); + +test('Object is Valid and digit is observable and isValid returns True', function () { + var digit = ko.observable(true); + var testObj = ko.observable('').extend({ digit: digit }); + + testObj(2); + + equal(testObj(), 2, 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is NOT Valid and digit is observable and isValid returns False', function () { + var digit = ko.observable(true); + var testObj = ko.observable('').extend({ digit: digit }); + + testObj('stuff'); + + equal(testObj(), 'stuff', 'observable still works'); + equal(testObj.isValid(), false, testObj.error()); +}); + +//#endregion + +//#region PhoneUS Validation +module('PhoneUS Validation'); + +test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ phoneUS: true }); + testObj(); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when null value is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ phoneUS: true }); + testObj(null); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid when empty string is present - Preserves Optional Properties', function () { + + var testObj = ko.observable().extend({ phoneUS: true }); + testObj(''); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is Valid and isValid returns True', function () { + var testObj = ko.observable('').extend({ phoneUS: true }); + + testObj('765-523-4569'); + + equal(testObj(), '765-523-4569', 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is NOT Valid and isValid returns False', function () { + var testObj = ko.observable('').extend({ phoneUS: true }); + + testObj(5); + + equal(testObj(), 5, 'observable still works'); + equal(testObj.isValid(), false, 'testObj is not valid'); +}); + +test('Object is Valid and phoneUS is observable and isValid returns True', function () { + var phoneUS = ko.observable(true); + var testObj = ko.observable('').extend({ phoneUS: phoneUS }); + + testObj('765-523-4569'); + + equal(testObj(), '765-523-4569', 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is NOT Valid and phoneUS is observable and isValid returns False', function () { + var phoneUS = ko.observable(true); + var testObj = ko.observable('').extend({ phoneUS: phoneUS }); + + testObj(5); + + equal(testObj(), 5, 'observable still works'); + equal(testObj.isValid(), false, 'testObj is not valid'); +}); +//#endregion + +//#region Equal tests +module("Equal Tests"); + +test('Object is Valid and isValid returns True', function () { + var compareObj = ko.observable(12); + var testObj = ko.observable('').extend({ equal: compareObj }); + + testObj(12); + + equal(testObj(), 12, 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is NOT Valid and isValid returns False', function () { + var compareObj = ko.observable(12); + var testObj = ko.observable('').extend({ equal: compareObj }); + + testObj(11); + + equal(testObj(), 11, 'observable still works'); + equal(testObj.isValid(), false, 'testObj is not valid'); +}); + +//#endregion + +//#region NotEqual tests +module("Not Equal Tests"); + +test('Object is Valid and isValid returns True', function () { + var compareObj = ko.observable(12); + var testObj = ko.observable('').extend({ notEqual: compareObj }); + + testObj(11); + + equal(testObj(), 11, 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is NOT Valid and isValid returns False', function () { + var compareObj = ko.observable(12); + var testObj = ko.observable('').extend({ notEqual: compareObj }); + + testObj(12); + + equal(testObj(), 12, 'observable still works'); + equal(testObj.isValid(), false, 'testObj is not valid'); +}); + +//#endregion + +//#region Unique tests +module("Unique Tests"); + +test('Object is Valid and isValid returns True', function () { + var compareObj = ko.observableArray([11, 12, 13]); + var testObj = ko.observable('').extend({ unique: { collection: compareObj } }); + + testObj(11); + + equal(testObj(), 11, 'observable still works'); + ok(testObj.isValid(), 'testObj is Valid'); +}); + +test('Object is NOT Valid and isValid returns False', function () { + var compareObj = ko.observableArray([11, 12, 13, 13]); + var testObj = ko.observable('').extend({ unique: { collection: compareObj } }); + + testObj(13); + + equal(testObj(), 13, 'observable still works'); + equal(testObj.isValid(), false, 'testObj is not valid'); +}); + +test('Correct unique validation behaviour for external values', function () { + var compareObj = ko.observableArray([11, 12, 13, 13]); + var testObj = ko.observable('').extend({ unique: { collection: compareObj, externalValue: true } }); + + testObj(12); + equal(testObj.isValid(), false, 'testObj is not valid'); + + testObj(13); + equal(testObj.isValid(), false, 'testObj is not valid'); + + testObj(10); + equal(testObj.isValid(), true, 'testObj is valid'); +}); + +test('Issue #365 - Correct unique validation behaviour for external values that are in the collection', function () { + var compareObj = ko.observableArray([11, 12, 13, 13]); + var testObj = ko.observable('').extend({ unique: { collection: compareObj, externalValue: 12 } }); + + testObj(12); + equal(testObj.isValid(), false, 'testObj is not valid'); + + testObj(10); + equal(testObj.isValid(), true, 'testObj is valid'); +}); + +//#endregion \ No newline at end of file diff --git a/Tests/test-runner.htm b/Tests/test-runner.htm index 92c2d34c..093cdcd8 100644 --- a/Tests/test-runner.htm +++ b/Tests/test-runner.htm @@ -11,6 +11,9 @@ + + + Knockout JS Validation Tests -

Knockout JS Validation Tests

-

-
-

-
    -
    test markup, will be hidden
    +
    +

    Knockout JS Validation Tests

    +

    +
    +

    +
      +
      test markup, will be hidden
      +
      - +
      From f4464da157ab91f3a68819b34fbbf3355d39c595 Mon Sep 17 00:00:00 2001 From: crissdev Date: Wed, 17 Dec 2014 22:14:26 +0200 Subject: [PATCH 109/165] Refactor tests to ease transition to QUnit 2.1+ Closes #485 --- Tests/api-tests.js | 328 +++++------ Tests/asserts.js | 105 ++++ Tests/rules-tests.js | 1045 ++++++++++++---------------------- Tests/test-runner.htm | 15 +- Tests/utils-tests.js | 123 ++-- Tests/validation-tests.js | 302 ++++------ Tests/validation-ui-tests.js | 786 +++++++++++-------------- 7 files changed, 1133 insertions(+), 1571 deletions(-) create mode 100644 Tests/asserts.js diff --git a/Tests/api-tests.js b/Tests/api-tests.js index 3822da42..09bb71b0 100644 --- a/Tests/api-tests.js +++ b/Tests/api-tests.js @@ -1,86 +1,78 @@ -/*global - module:false, - equal:false, - notEqual:false, - strictEqual:false, - deepEqual:false, - test:false, - ok:false, - asyncTest:false, - start: false, - stop: false, - expect: false -*/ +/*global QUnit:false*/ + //#region Manual Validation -module("Manual Validation"); -test("setError sets isValid and error message", function () { + +QUnit.module('Manual Validation'); + +QUnit.test('setError sets isValid and error message', function(assert) { var testObj = ko.observable(); testObj.extend({ validatable: true }); //check initial validation state - ok(testObj.isValid()); - equal(testObj.error(), null); + assert.ok(testObj.isValid()); + assert.equal(testObj.error(), null); //manually set an error - testObj.setError("oh no!"); + testObj.setError('oh no!'); //check state was set - ok(!testObj.isValid()); - equal("oh no!", testObj.error()); + assert.ok(!testObj.isValid()); + assert.equal('oh no!', testObj.error()); }); -test("clearError clears manually-specified error", function () { +QUnit.test('clearError clears manually-specified error', function(assert) { var testObj = ko.observable(); testObj.extend({ validatable: true }); - testObj.setError("oh no!"); + testObj.setError('oh no!'); //fail the validation - ok(!testObj.isValid()); + assert.ok(!testObj.isValid()); //clear the validation var result = testObj.clearError(); - equal(testObj, result, "The result should be returned to support chaining"); + assert.equal(testObj, result, 'The result should be returned to support chaining'); //check state was cleared - ok(testObj.isValid()); - equal(testObj.error(), null); + assert.ok(testObj.isValid()); + assert.equal(testObj.error(), null); }); -test("clearError clears automatic errors", function () { +QUnit.test('clearError clears automatic errors', function(assert) { var testObj = ko.observable(5); testObj.extend({ min: 6 }); //check initial state - ok(!testObj.isValid()); + assert.ok(!testObj.isValid()); var result = testObj.clearError(); - equal(testObj, result, "The result should be returned to support chaining"); + assert.equal(testObj, result, 'The result should be returned to support chaining'); //check validation was cleared - ok(testObj.isValid()); - equal(testObj.error(), null); + assert.ok(testObj.isValid()); + assert.equal(testObj.error(), null); }); //#endregion //#region Grouping Tests -module('Grouping Tests'); -test('Error Grouping works', function () { +QUnit.module('Grouping Tests'); + +QUnit.test('Error Grouping works', function(assert) { var vm = { - firstName: ko.observable().extend({ required: { message: "Message 1" } }), - lastName: ko.observable().extend({ required: { message: "Message 2" } }) + firstName: ko.observable().extend({ required: { message: 'Message 1' } }), + lastName: ko.observable().extend({ required: { message: 'Message 2' } }) }; var errors = ko.validation.group(vm); - equal(errors().length, 2, 'Grouping correctly finds 2 invalid properties'); - equal(errors()[0], "Message 1", "The error itself should be returned, not the observable"); - equal(errors()[1], "Message 2", "The error itself should be returned, not the observable"); + assert.equal(errors().length, 2, 'Grouping correctly finds 2 invalid properties'); + assert.equal(errors()[0], 'Message 1', 'The error itself should be returned, not the observable'); + assert.equal(errors()[1], 'Message 2', 'The error itself should be returned, not the observable'); }); -test('Nested Grouping works - Observable', function () { +QUnit.test('Nested Grouping works - Observable', function(assert) { var vm = { one: ko.observable().extend({ required: true }), two: { @@ -95,10 +87,10 @@ test('Nested Grouping works - Observable', function () { var errors = ko.validation.group(vm, { deep: true, observable: true }); - equal(errors().length, 3, 'Grouping correctly finds 3 invalid properties'); + assert.equal(errors().length, 3, 'Grouping correctly finds 3 invalid properties'); }); -test('Nested Grouping works - Not Observable', function () { +QUnit.test('Nested Grouping works - Not Observable', function(assert) { var vm = { one: ko.observable().extend({ required: true }), two: { @@ -113,28 +105,28 @@ test('Nested Grouping works - Not Observable', function () { var errors = ko.validation.group(vm, { deep: true, observable: false }); - equal(errors().length, 3, 'Grouping correctly finds 3 invalid properties'); + assert.equal(errors().length, 3, 'Grouping correctly finds 3 invalid properties'); }); -test('Nested grouping finds items in observableArrays - observable', function () { +QUnit.test('Nested grouping finds items in observableArrays - observable', function(assert) { var vm = { array: ko.observableArray([{ one: ko.observable().extend({ required: true }) }]) }; var errors = ko.validation.group(vm, { deep: true, observable: true }); - equal(errors().length, 1, 'Grouping finds property on object in observableArray'); + assert.equal(errors().length, 1, 'Grouping finds property on object in observableArray'); }); -test('Nested grouping does not add items newly inserted into observableArrays to result - observable, not live', function () { +QUnit.test('Nested grouping does not add items newly inserted into observableArrays to result - observable, not live', function(assert) { var vm = { array: ko.observableArray() }; var errors = ko.validation.group(vm, { deep: true, observable: true, live: false }); vm.array.push({ one: ko.observable().extend({ required: true }) }); - equal(errors().length, 0, 'grouping does not add newly items newly inserted into observableArrays to result'); + assert.equal(errors().length, 0, 'grouping does not add newly items newly inserted into observableArrays to result'); }); -test('Nested grouping adds items newly inserted into an observableArrays nested in an object in an observableArray to result - observable, live', function () { +QUnit.test('Nested grouping adds items newly inserted into an observableArrays nested in an object in an observableArray to result - observable, live', function(assert) { var vm = { array: ko.observableArray() }; var errors = ko.validation.group(vm, { deep: true, observable: true, live: true }); @@ -142,68 +134,67 @@ test('Nested grouping adds items newly inserted into an observableArrays nested vm.array.push({ array: ko.observableArray() }); vm.array()[0].array.push({ one: ko.observable().extend({ required: true }) }); - equal(errors().length, 1, 'grouping adds newly items newly inserted into observableArrays to result'); + assert.equal(errors().length, 1, 'grouping adds newly items newly inserted into observableArrays to result'); }); -test('Nested grouping adds items newly inserted into observableArrays to result - observable, live', function () { +QUnit.test('Nested grouping adds items newly inserted into observableArrays to result - observable, live', function(assert) { var vm = { array: ko.observableArray() }; var errors = ko.validation.group(vm, { deep: true, observable: true, live: true }); vm.array.push({ one: ko.observable().extend({ required: true }) }); - equal(errors().length, 1, 'grouping adds newly items newly inserted into observableArrays to result'); + assert.equal(errors().length, 1, 'grouping adds newly items newly inserted into observableArrays to result'); }); -test('Nested grouping ignores items nested in destroyed objects - not observable', function () { +QUnit.test('Nested grouping ignores items nested in destroyed objects - not observable', function(assert) { var obj = { nested: ko.observable().extend({ required: true }) }; function getErrorCount() { return ko.validation.group(obj, { deep: true, observable: false, live: false })().length; } - equal(getErrorCount(), 1, 'obj is not destroyed and should return nested\'s error'); + assert.equal(getErrorCount(), 1, 'obj is not destroyed and should return nested\'s error'); obj._destroy = true; - equal(getErrorCount(), 0, 'obj is destroyed and nested therefore ignored'); + assert.equal(getErrorCount(), 0, 'obj is destroyed and nested therefore ignored'); }); -test('Nested grouping ignores items nested in destroyed objects - observable, live', function () { +QUnit.test('Nested grouping ignores items nested in destroyed objects - observable, live', function(assert) { var obj = { nested: ko.observable().extend({ required: true }) }; var array = ko.observableArray([obj]); var vm = { array: array }; var errors = ko.validation.group(vm, { deep: true, observable: true, live: true }); - equal(errors().length, 1, 'obj is not yet destroyed and nested therefore invalid'); + assert.equal(errors().length, 1, 'obj is not yet destroyed and nested therefore invalid'); array.destroy(obj); - equal(errors().length, 0, 'obj is destroyed and nested therefore ignored'); + assert.equal(errors().length, 0, 'obj is destroyed and nested therefore ignored'); }); -test('Nested grouping does not cause the reevaluation of computeds depending on the result for every observable', function () { +QUnit.test('Nested grouping does not cause the reevaluation of computeds depending on the result for every observable', function(assert) { var vm = { array: ko.observableArray() }; var errors = ko.validation.group(vm, { deep: true, observable: true, live: true }); var computedHitCount = 0; - var computed = ko.computed(function () { + var computed = ko.computed(function() { computedHitCount++; errors(); }); vm.array.push({ one: ko.observable().extend({ required: true }) }); - equal(computedHitCount, 2, 'first one while creating the computed, second one for adding the item'); + assert.equal(computedHitCount, 2, 'first one while creating the computed, second one for adding the item'); vm.array.push({ one: ko.observable().extend({ required: true }) }); - equal(computedHitCount, 3, 'Only one additional re-evaluation should have been triggered'); + assert.equal(computedHitCount, 3, 'Only one additional re-evaluation should have been triggered'); vm.array.push({ one: ko.observable().extend({ required: true }) }); - equal(computedHitCount, 4, 'Only one additional re-evaluation should have been triggered'); - + assert.equal(computedHitCount, 4, 'Only one additional re-evaluation should have been triggered'); }); -test('Nested grouping adds items newly inserted into observableArrays to result - cleares validatables before traversing again - observable, live', function () { +QUnit.test('Nested grouping adds items newly inserted into observableArrays to result - clears validatables before traversing again - observable, live', function(assert) { var vm = { array: ko.observableArray() }; var errors = ko.validation.group(vm, { deep: true, observable: true, live: true }); @@ -211,14 +202,16 @@ test('Nested grouping adds items newly inserted into observableArrays to result vm.array.push({ one: ko.observable().extend({ required: true }) }); vm.array.push({ one: ko.observable().extend({ required: true }) }); - equal(errors().length, 2, 'validatables are added only once'); + assert.equal(errors().length, 2, 'validatables are added only once'); }); //#endregion //#region validatedObservable -module('validatedObservable Tests'); -test('validatedObservable is Valid', function () { + +QUnit.module('validatedObservable Tests'); + +QUnit.test('validatedObservable is Valid', function(assert) { var obj = ko.validatedObservable({ testObj: ko.observable('').extend({ minLength: 5 }), @@ -228,12 +221,11 @@ test('validatedObservable is Valid', function () { obj().testObj('something'); obj().testObj2('eric'); - ok(obj(), 'observable works'); - ok(obj.isValid(), 'observable is valid'); - + assert.ok(obj(), 'observable works'); + assert.ok(obj.isValid(), 'observable is valid'); }); -test('validatedObservable is not Valid', function () { +QUnit.test('validatedObservable is not Valid', function(assert) { var obj = ko.validatedObservable({ testObj: ko.observable('').extend({ minLength: 5 }), @@ -243,12 +235,11 @@ test('validatedObservable is not Valid', function () { obj().testObj('some');// not length of 5 obj().testObj2('eric'); - ok(obj(), 'observable works'); - ok(!obj.isValid(), obj.errors()[0]); - + assert.ok(obj(), 'observable works'); + assert.ok(!obj.isValid(), obj.errors()[0]); }); -test('validatedObservable is first Valid then made InValid', function () { +QUnit.test('validatedObservable is first Valid then made InValid', function(assert) { var obj = ko.validatedObservable({ testObj: ko.observable('').extend({ minLength: 5 }), @@ -262,23 +253,21 @@ test('validatedObservable is first Valid then made InValid', function () { //now make it invalid obj().testObj('some'); - ok(obj(), 'observable works'); - ok(!obj.isValid(), obj.errors()[0]); - + assert.ok(obj(), 'observable works'); + assert.ok(!obj.isValid(), obj.errors()[0]); }); -test('validatedObservable does not show error message when not modified', function () { +QUnit.test('validatedObservable does not show error message when not modified', function(assert) { var obj = ko.validatedObservable({ testObj: ko.observable('a').extend({ minLength: 5 }), testObj2: ko.observable('').extend({ required: true }) }); - ok(obj(), 'observable works'); - ok(!obj.errors.isAnyMessageShown(), 'validation error message is hidden'); - + assert.ok(obj(), 'observable works'); + assert.ok(!obj.errors.isAnyMessageShown(), 'validation error message is hidden'); }); -test('validatedObservable does not show error message when modified but correct', function () { +QUnit.test('validatedObservable does not show error message when modified but correct', function(assert) { var obj = ko.validatedObservable({ testObj: ko.observable('a').extend({ minLength: 5 }), testObj2: ko.observable('').extend({ required: true }) @@ -287,12 +276,11 @@ test('validatedObservable does not show error message when modified but correct' obj().testObj('12345'); obj().testObj2('a'); - ok(obj(), 'observable works'); - ok(!obj.errors.isAnyMessageShown(), 'validation error message is hidden'); - + assert.ok(obj(), 'observable works'); + assert.ok(!obj.errors.isAnyMessageShown(), 'validation error message is hidden'); }); -test('validatedObservable show error message when at least one invalid and modified', function () { +QUnit.test('validatedObservable show error message when at least one invalid and modified', function(assert) { var obj = ko.validatedObservable({ testObj: ko.observable('a').extend({ minLength: 5 }), testObj2: ko.observable('').extend({ required: true }) @@ -300,36 +288,32 @@ test('validatedObservable show error message when at least one invalid and modif obj().testObj.isModified(true); - ok(obj(), 'observable works'); - ok(obj.errors.isAnyMessageShown(), 'validation error message is shown'); - + assert.ok(obj(), 'observable works'); + assert.ok(obj.errors.isAnyMessageShown(), 'validation error message is shown'); }); -test('validatedObservable is Valid when not modified', function () { - +QUnit.test('validatedObservable is Valid when not modified', function(assert) { var obj = ko.validatedObservable({ testObj: ko.observable('12345').extend({ minLength: 5 }), testObj2: ko.observable('a').extend({ required: true }) }); - ok(obj(), 'observable works'); - ok(obj.isValid(), 'observable is valid'); - + assert.ok(obj(), 'observable works'); + assert.ok(obj.isValid(), 'observable is valid'); }); -test('validatedObservable is not Valid when not modified', function () { +QUnit.test('validatedObservable is not Valid when not modified', function(assert) { var obj = ko.validatedObservable({ testObj: ko.observable('').extend({ minLength: 5 }), testObj2: ko.observable('').extend({ required: true }) }); - ok(obj(), 'observable works'); - ok(!obj.isValid(), obj.errors()[0]); - + assert.ok(obj(), 'observable works'); + assert.ok(!obj.isValid(), obj.errors()[0]); }); -test('Issue #454 - validatedObservable throws when config option grouping.observable is false', function () { +QUnit.test('Issue #454 - validatedObservable throws when config option grouping.observable is false', function(assert) { ko.validation.init({grouping: {observable: false}}, true); var obj = ko.validatedObservable({ @@ -338,16 +322,17 @@ test('Issue #454 - validatedObservable throws when config option grouping.observ admin: ko.observable().extend({required: true}) }); - ok(obj(), 'observable works'); - ok(!obj.isValid(), obj.errors()[0]); + assert.ok(obj(), 'observable works'); + assert.ok(!obj.isValid(), obj.errors()[0]); }); //#endregion //#region setRules Tests -module("setRules Tests"); -test("setRules applies rules to all properties", function () { +QUnit.module('setRules Tests'); + +QUnit.test('setRules applies rules to all properties', function(assert) { var definition = { property1: { required: true, @@ -358,8 +343,8 @@ test("setRules applies rules to all properties", function () { child: { property2: { pattern: { - params: "^[a-z0-9].$", - message: "Only AlphaNumeric please" + params: '^[a-z0-9].$', + message: 'Only AlphaNumeric please' } }, grandchild: { @@ -396,36 +381,36 @@ test("setRules applies rules to all properties", function () { ko.validation.setRules(target, definition); //check that all rules have been applied - deepEqual(target.property1.rules(), [ - { rule: "required", params: true }, - { rule: "min", params: 10 }, - { rule: "max", params: 99 } + assert.deepEqual(target.property1.rules(), [ + { rule: 'required', params: true }, + { rule: 'min', params: 10 }, + { rule: 'max', params: 99 } ]); - deepEqual(target.child.property2.rules(), [ - { rule: "pattern", message: "Only AlphaNumeric please", params: "^[a-z0-9].$", condition: undefined } + assert.deepEqual(target.child.property2.rules(), [ + { rule: 'pattern', message: 'Only AlphaNumeric please', params: '^[a-z0-9].$', condition: undefined } ]); - deepEqual(target.child.grandchild.property3.rules(), [ - { rule: "number", params: true } + assert.deepEqual(target.child.grandchild.property3.rules(), [ + { rule: 'number', params: true } ]); for (var i = 0; i < target.nestedArray().length; i++) { - deepEqual(target.nestedArray()[i].property4.rules(), [ - { rule: "email", params: true } + assert.deepEqual(target.nestedArray()[i].property4.rules(), [ + { rule: 'email', params: true } ]); } //check that ignored properties have not had rules added - ok(!target.ignoredProperty.rules); - ok(!target.child.ignoredProperty.rules); - ok(!target.child.grandchild.ignoredProperty.rules); - ok(!target.nestedArray()[0].ignoredProperty.rules); - ok(!target.nestedArray()[1].ignoredProperty.rules); - ok(!target.nestedArray()[2].ignoredProperty.rules); + assert.ok(!target.ignoredProperty.rules); + assert.ok(!target.child.ignoredProperty.rules); + assert.ok(!target.child.grandchild.ignoredProperty.rules); + assert.ok(!target.nestedArray()[0].ignoredProperty.rules); + assert.ok(!target.nestedArray()[1].ignoredProperty.rules); + assert.ok(!target.nestedArray()[2].ignoredProperty.rules); }); -test('Issue #461 - validatedObservable works with nested view models if grouping.deep is true', function() { +QUnit.test('Issue #461 - validatedObservable works with nested view models if grouping.deep is true', function(assert) { ko.validation.init({grouping: {deep: true}}, true); function Inner() { @@ -438,13 +423,13 @@ test('Issue #461 - validatedObservable works with nested view models if grouping inner: new Inner() }); - ok(obj(), 'observable works'); - equal(obj.errors().length, 1, 'Must have one error reported'); - equal(obj.errors()[0], 'admins is required'); - ok(!obj.isValid(), obj.errors()[0]); + assert.ok(obj(), 'observable works'); + assert.equal(obj.errors().length, 1, 'Must have one error reported'); + assert.equal(obj.errors()[0], 'admins is required'); + assert.ok(!obj.isValid(), obj.errors()[0]); }); -test('Issue #461 - validatedObservable works with nested view models if grouping.deep is true using options', function() { +QUnit.test('Issue #461 - validatedObservable works with nested view models if grouping.deep is true using options', function(assert) { ko.validation.init({grouping: {deep: false}}, true); function Inner() { @@ -457,18 +442,19 @@ test('Issue #461 - validatedObservable works with nested view models if grouping inner: new Inner() }, {deep: true}); - ok(obj(), 'observable works'); - equal(obj.errors().length, 1, 'Must have one error reported'); - equal(obj.errors()[0], 'admins is required'); - ok(!obj.isValid(), obj.errors()[0]); + assert.ok(obj(), 'observable works'); + assert.equal(obj.errors().length, 1, 'Must have one error reported'); + assert.equal(obj.errors()[0], 'admins is required'); + assert.ok(!obj.isValid(), obj.errors()[0]); }); //#endregion //#region Removing Validation -module('Removing Validation Tests'); -test('Basic Removal', function () { +QUnit.module('Removing Validation Tests'); + +QUnit.test('Basic Removal', function(assert) { var testObj = ko.observable('') .extend({ min: 2 }); @@ -476,45 +462,41 @@ test('Basic Removal', function () { var testFlag = false; - equal(testObj(), 3, 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.equal(testObj(), 3, 'observable still works'); + assert.ok(testObj.isValid(), 'testObj is Valid'); - testObj.isValid.subscribe(function () { + testObj.isValid.subscribe(function() { testFlag = true; }); testObj.extend({ validatable: false }); - ok(!testObj.isValid, 'Validation features removed'); + assert.ok(!testObj.isValid, 'Validation features removed'); testObj(1); - ok(!testFlag, 'Subscriptions to isValid didnt fire'); - + assert.ok(!testFlag, 'Subscriptions to isValid didnt fire'); }); + //#endregion //#region validation process tests -module("Validation process", { - setup: function () { - var isStarted = false; - ko.validation._validateObservable = ko.validation.validateObservable; - ko.validation.validateObservable = function () { - ok(true, "Triggered only once"); - if (!isStarted) { - isStarted = true; - start(); - } - return ko.validation._validateObservable.apply(this, arguments); - }; - }, - - teardown: function () { - ko.validation.validateObservable = ko.validation._validateObservable; +QUnit.module('Validation process', { + afterEach: function() { + ko.validation.reset(); } }); -asyncTest("can be throttled using global configuration", function () { - expect(2); // one for initialization and when value changed +QUnit.test('can be throttled using global configuration', function(assert) { + var done = assert.async(); + assert.expect(0); + + var _validateObservable = ko.validation.validateObservable; + ko.validation.validateObservable = function() { + var result = _validateObservable.apply(this, arguments); + ko.validation.validateObservable = _validateObservable; + done(); + return result; + }; ko.validation.init({ validate: { @@ -523,14 +505,21 @@ asyncTest("can be throttled using global configuration", function () { }, true); var observable = ko.observable().extend({ validatable: true }); - observable("1"); + observable('1'); observable.extend({ minLength: 2 }); - - ko.validation.init({ validate: {} }, true); }); -asyncTest("can be throttled using using local configuration", function () { - expect(2); // one for initialization and when value changed +QUnit.test('can be throttled using using local configuration', function(assert) { + var done = assert.async(); + assert.expect(0); + + var _validateObservable = ko.validation.validateObservable; + ko.validation.validateObservable = function() { + var result = _validateObservable.apply(this, arguments); + ko.validation.validateObservable = _validateObservable; + done(); + return result; + }; var observable = ko.observable().extend({ validatable: { @@ -539,29 +528,28 @@ asyncTest("can be throttled using using local configuration", function () { }); observable.extend({ minLength: 2 }); - observable("1"); + observable('1'); }); //#endregion -module("Formatting Tests"); +QUnit.module('Formatting Tests'); -test("formatMessage passes observable to function", function () { +QUnit.test('formatMessage passes observable to function', function(assert) { var inParams = { value: 123 }, inObservable = ko.observable(); ko.validation.formatMessage(function (params, observable) { - equal(params, inParams); - equal(observable, inObservable); + assert.equal(params, inParams); + assert.equal(observable, inObservable); }, inParams, inObservable); }); -test("formatMessage may use multiple replacements", function() { +QUnit.test('formatMessage may use multiple replacements', function(assert) { var params = [1, 5], message = 'Value must be between {0} and {1}.', obsv = ko.observable(10); var result = ko.validation.formatMessage(message, params, obsv); - equal(result, 'Value must be between 1 and 5.'); - + assert.equal(result, 'Value must be between 1 and 5.'); }); diff --git a/Tests/asserts.js b/Tests/asserts.js new file mode 100644 index 00000000..8edcf8fd --- /dev/null +++ b/Tests/asserts.js @@ -0,0 +1,105 @@ +/*global QUnit:false*/ + + +//#region Custom assertions to ensure thoroughly testing + +/** + * Verifies that observable has the expected value, is valid and error message is empty. + * This helper can be used for checking against any rule applied to an observable. + * @param observable The observable to check. + * @param value The expected value of the observable. + */ +QUnit.assert.observableIsValid = function(observable, value) { + this.strictEqual(observable(), value, 'observable still works'); + this.strictEqual(observable.isValid(), true, 'observable is valid'); + this.strictEqual(observable.error(), null, 'message is empty'); +}; + +/** + * Verifies that observable has the expected value, is not valid and has the right error message. + * @param observable The observable to check + * @param value The expected value of the observable + * @param ruleMessage The expected value returned by error() method of the observable. + */ +QUnit.assert.observableIsNotValid = function(observable, value, ruleMessage) { + this.strictEqual(observable(), value, 'observable still works'); + this.strictEqual(observable.isValid(), false, 'observable is not valid'); + this.strictEqual(observable.error(), ruleMessage, 'message is correct'); +}; + +QUnit.assert.violatesRequiredRule = function(observable, value, customMessage) { + var ruleMessage = customMessage || 'This field is required.'; + this.observableIsNotValid(observable, value, ruleMessage); +}; + +QUnit.assert.violatesMinRule = function(observable, value, minValue, customMessage) { + var ruleMessage = customMessage || 'Please enter a value greater than or equal to ' + minValue.toString() + '.'; + this.observableIsNotValid(observable, value, ruleMessage); +}; + +QUnit.assert.violatesMaxRule = function(observable, value, maxValue, customMessage) { + var ruleMessage = customMessage || 'Please enter a value less than or equal to ' + maxValue.toString() + '.'; + this.observableIsNotValid(observable, value, ruleMessage); +}; + +QUnit.assert.violatesMinLengthRule = function(observable, value, minLength, customMessage) { + var ruleMessage = customMessage || 'Please enter at least ' + minLength.toString() + ' characters.'; + this.observableIsNotValid(observable, value, ruleMessage); +}; + +QUnit.assert.violatesMaxLengthRule = function(observable, value, maxLength, customMessage) { + var ruleMessage = customMessage || 'Please enter no more than ' + maxLength.toString() + ' characters.'; + this.observableIsNotValid(observable, value, ruleMessage); +}; + +QUnit.assert.violatesPatternRule = function(observable, value, customMessage) { + var ruleMessage = customMessage || 'Please check this value.'; + this.observableIsNotValid(observable, value, ruleMessage); +}; + +QUnit.assert.violatesStepRule = function(observable, value, step, customMessage) { + var ruleMessage = customMessage || 'The value must increment by ' + step.toString() + '.'; + this.observableIsNotValid(observable, value, ruleMessage); +}; + +QUnit.assert.violatesEmailRule = function(observable, value, customMessage) { + var ruleMessage = customMessage || 'Please enter a proper email address.'; + this.observableIsNotValid(observable, value, ruleMessage); +}; + +QUnit.assert.violatesDateRule = function(observable, value, customMessage) { + var ruleMessage = customMessage || 'Please enter a proper date.'; + this.observableIsNotValid(observable, value, ruleMessage); +}; + +QUnit.assert.violatesNumberRule = function(observable, value, customMessage) { + var ruleMessage = customMessage || 'Please enter a number.'; + this.observableIsNotValid(observable, value, ruleMessage); +}; + +QUnit.assert.violatesDigitRule = function(observable, value, customMessage) { + var ruleMessage = customMessage || 'Please enter a digit.'; + this.observableIsNotValid(observable, value, ruleMessage); +}; + +QUnit.assert.violatesPhoneUSRule = function(observable, value, customMessage) { + var ruleMessage = customMessage || 'Please specify a valid phone number.'; + this.observableIsNotValid(observable, value, ruleMessage); +}; + +QUnit.assert.violatesMustEqualRule = function(observable, value, customMessage) { + var ruleMessage = customMessage || 'Values must equal.'; + this.observableIsNotValid(observable, value, ruleMessage); +}; + +QUnit.assert.violatesNotEqualRule = function(observable, value, customMessage) { + var ruleMessage = customMessage || 'Please choose another value.'; + this.observableIsNotValid(observable, value, ruleMessage); +}; + +QUnit.assert.violatesUniqueRule = function(observable, value, customMessage) { + var ruleMessage = customMessage || 'Please make sure the value is unique.'; + this.observableIsNotValid(observable, value, ruleMessage); +}; + +//#endregion diff --git a/Tests/rules-tests.js b/Tests/rules-tests.js index 3ae191fd..3357b27d 100644 --- a/Tests/rules-tests.js +++ b/Tests/rules-tests.js @@ -1,572 +1,400 @@ -/*global - module:false, - equal:false, - notEqual:false, - strictEqual:false, - deepEqual:false, - test:false, - ok:false, - asyncTest:false, - start: false, - stop: false, - expect: false -*/ +/*global QUnit:false*/ -//#region Required Validation - -module('Required Validation'); -test('Object is Valid and isValid returns True', function () { +//#region Required Validation - var testObj = ko.observable('') - .extend({ required: true }); +QUnit.module('Required Validation'); +QUnit.test('Object is Valid and isValid returns True', function(assert) { + var testObj = ko.observable('').extend({ required: true }); testObj('something'); - - equal(testObj(), 'something', 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, 'something'); }); -test('Object is NOT Valid and isValid returns False', function () { - - var testObj = ko.observable('') - .extend({ required: true }); - - equal(testObj(), '', 'observable still works'); - equal(testObj.isValid(), false, 'testObj is not valid'); +QUnit.test('Object is NOT Valid and isValid returns False', function(assert) { + var testObj = ko.observable('').extend({ required: true }); + assert.violatesRequiredRule(testObj, ''); }); -test('Zero is a valid value for required', function () { - - var testObj = ko.observable(0) - .extend({ required: true }); - - equal(testObj(), 0, 'observable still works'); - equal(testObj.isValid(), true, 'testObj is valid'); +QUnit.test('Zero is a valid value for required', function(assert) { + var testObj = ko.observable(0).extend({ required: true }); + assert.observableIsValid(testObj, 0); }); -test('Empty spaces is not a valid value for required', function () { - - var testObj = ko.observable(' ') - .extend({ required: true }); - - equal(testObj(), ' ', 'observable still works'); - equal(testObj.isValid(), false, 'testObj is valid'); +QUnit.test('Empty spaces is not a valid value for required', function(assert) { + var testObj = ko.observable(' ').extend({ required: true }); + assert.violatesRequiredRule(testObj, ' '); }); -test('Issue #90 - "required: false" doesnt force validation', function () { - - var testObj = ko.observable() - .extend({ required: false }); - - equal(testObj.isValid(), true, 'testObj is valid without value'); +QUnit.test('Issue #90 - "required: false" doesnt force validation', function(assert) { + var testObj = ko.observable().extend({ required: false }); + assert.observableIsValid(testObj, undefined); testObj('blah'); - equal(testObj.isValid(), true, 'testObj is valid with value'); + assert.observableIsValid(testObj, 'blah'); testObj(null); - equal(testObj.isValid(), true, 'testObj is valid without value after set/unset'); + assert.observableIsValid(testObj, null); }); -test("Undefined params should not cause errors", function () { +QUnit.test('Undefined params should not cause errors', function(assert) { var undefinedParams = ko.observable().extend({ required: undefined }), nullParams = ko.observable().extend({ required: null }); - ok(true, "No errors whilst adding rules? Awesome"); -}); + //TODO: Should required rule pass when params is null (it's not quite expected to fail with undefined but pass with null) -test("Issue #376 - empty string should pass validation when required = false", function () { - var observable = ko.observable("").extend({ required: false }); + assert.violatesRequiredRule(undefinedParams, undefined); + assert.observableIsValid(nullParams, undefined); +}); - ok(observable.isValid(), "Empty string should be valid"); +QUnit.test('Issue #376 - empty string should pass validation when required = false', function(assert) { + var testObj = ko.observable('').extend({ required: false }); + assert.observableIsValid(testObj, ''); }); //#endregion //#region Min Validation -module('Min Validation'); - -test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { +QUnit.module('Min Validation'); +QUnit.test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ min: 2 }); - testObj(); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, undefined); }); -test('Object is Valid when null value is present - Preserves Optional Properties', function () { - +QUnit.test('Object is Valid when null value is present - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ min: 2 }); testObj(null); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, null); }); -test('Object is Valid when empty string is present - Preserves Optional Properties', function () { - +QUnit.test('Object is Valid when empty string is present - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ min: 2 }); testObj(''); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, ''); }); -test('Object is Valid and isValid returns True', function () { - var testObj = ko.observable('') - .extend({ min: 2 }); - +QUnit.test('Object is Valid and isValid returns True', function(assert) { + var testObj = ko.observable('').extend({ min: 2 }); testObj(3); - - equal(testObj(), 3, 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, 3); }); -test('Object is Valid and isValid returns True (with min: 0)', function () { - var testObj = ko.observable('') - .extend({ min: 0 }); - - testObj("0"); - - equal(testObj(), "0", 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); +QUnit.test('Object is Valid and isValid returns True (with min: 0)', function(assert) { + var testObj = ko.observable('').extend({ min: 0 }); + testObj('0'); + assert.observableIsValid(testObj, '0'); }); -test('Object is NOT Valid and isValid returns False', function () { - var testObj = ko.observable('') - .extend({ min: 2 }); - +QUnit.test('Object is NOT Valid and isValid returns False', function(assert) { + var testObj = ko.observable('').extend({ min: 2 }); testObj(1); - - equal(testObj(), 1, 'observable still works'); - equal(testObj.isValid(), false, 'testObj is not valid'); - equal(testObj.error(), 'Please enter a value greater than or equal to 2.', 'Message needs to be formatted correctly'); + assert.violatesMinRule(testObj, 1, 2); }); -test('Object is NOT Valid and isValid returns False and min is observable', function () { +QUnit.test('Object is NOT Valid and isValid returns False and min is observable', function(assert) { var minValue = ko.observable(3); - var testObj = ko.observable('') - .extend({ min: minValue }); - + var testObj = ko.observable('').extend({ min: minValue }); testObj(1); - - equal(testObj(), 1, 'observable still works'); - equal(testObj.isValid(), false, 'testObj is not valid'); - equal(testObj.error(), 'Please enter a value greater than or equal to 3.', 'Message needs to be formatted correctly'); + assert.violatesMinRule(testObj, 1, 3); }); -test('Object is Valid and isValid returns True and min is observable', function () { +QUnit.test('Object is Valid and isValid returns True and min is observable', function(assert) { var minValue = ko.observable(3); - var testObj = ko.observable('') - .extend({ min: minValue }); - + var testObj = ko.observable('').extend({ min: minValue }); testObj(4); - - equal(testObj(), 4, 'observable still works'); - equal(testObj.isValid(), true, 'testObj is valid'); + assert.observableIsValid(testObj, 4); }); -test('Object is Valid and isValid returns True and min is date', function () { - var obj = new Date(2012, 05, 04); - var testObj = ko.observable('') - .extend({ min: new Date(2012, 03, 04) }); - - testObj(obj); - - equal(testObj(), obj, 'observable still works'); - equal(testObj.isValid(), true, 'testObj is valid'); +QUnit.test('Object is Valid and isValid returns True and min is date', function(assert) { + var obj = new Date(2012, 5, 4); + var testObj = ko.observable('').extend({ min: new Date(2012, 3, 4) }); + testObj(obj); + assert.observableIsValid(testObj, obj); }); -test('Object is NOT Valid and isValid returns False and min is date', function () { - var obj = new Date(2011, 05, 04); - var testObj = ko.observable('') - .extend({ min: new Date(2012, 03, 04) }); - - testObj(obj); - - equal(testObj(), obj, 'observable still works'); - equal(testObj.isValid(), false, 'testObj is not valid'); +QUnit.test('Object is NOT Valid and isValid returns False and min is date', function(assert) { + var obj = new Date(2011, 5, 4); + var minValue = new Date(2012, 3, 4); + var testObj = ko.observable('').extend({ min: minValue }); + testObj(obj); + assert.violatesMinRule(testObj, obj, minValue); }); //#endregion //#region Max Validation -module('Max Validation'); - -test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { +QUnit.module('Max Validation'); +QUnit.test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ max: 2 }); - testObj(); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, undefined); }); -test('Object is Valid when null value is present - Preserves Optional Properties', function () { - +QUnit.test('Object is Valid when null value is present - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ max: 2 }); testObj(null); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, null); }); -test('Object is Valid when empty string is present - Preserves Optional Properties', function () { - +QUnit.test('Object is Valid when empty string is present - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ max: 2 }); testObj(''); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, ''); }); -test('Object is Valid and isValid returns True', function () { - var testObj = ko.observable('') - .extend({ max: 5 }); - +QUnit.test('Object is Valid and isValid returns True', function(assert) { + var testObj = ko.observable('').extend({ max: 5 }); testObj(3); - - equal(testObj(), 3, 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, 3); }); -test('Object is NOT Valid and isValid returns False', function () { - var testObj = ko.observable('') - .extend({ max: 5 }); - +QUnit.test('Object is NOT Valid and isValid returns False', function(assert) { + var testObj = ko.observable('').extend({ max: 5 }); testObj(6); - - equal(testObj(), 6, 'observable still works'); - equal(testObj.isValid(), false, 'testObj is not valid'); - equal(testObj.error(), 'Please enter a value less than or equal to 5.', 'Message needs to be formatted correctly'); + assert.violatesMaxRule(testObj, 6, 5); }); -test('Object is NOT Valid and isValid returns False and max is observable', function () { +QUnit.test('Object is NOT Valid and isValid returns False and max is observable', function(assert) { var minValue = ko.observable(3); - var testObj = ko.observable('') - .extend({ max: minValue }); - + var testObj = ko.observable('').extend({ max: minValue }); testObj(4); - - equal(testObj(), 4, 'observable still works'); - equal(testObj.isValid(), false, 'testObj is not valid'); - equal(testObj.error(), 'Please enter a value less than or equal to 3.', 'Message needs to be formatted correctly'); + assert.violatesMaxRule(testObj, 4, minValue()); }); -test('Object is Valid and isValid returns True and max is observable', function () { +QUnit.test('Object is Valid and isValid returns True and max is observable', function(assert) { var minValue = ko.observable(3); - var testObj = ko.observable('') - .extend({ max: minValue }); - + var testObj = ko.observable('').extend({ max: minValue }); testObj(1); - - equal(testObj(), 1, 'observable still works'); - equal(testObj.isValid(), true, 'testObj is valid'); + assert.observableIsValid(testObj, 1); }); -test('Object is Valid and isValid returns True and max is date', function () { - var obj = new Date(2011, 05, 04); - var testObj = ko.observable('') - .extend({ max: new Date(2012, 03, 04) }); - - testObj(obj); - - equal(testObj(), obj, 'observable still works'); - equal(testObj.isValid(), true, 'testObj is valid'); +QUnit.test('Object is Valid and isValid returns True and max is date', function(assert) { + var obj = new Date(2011, 5, 4); + var testObj = ko.observable('').extend({ max: new Date(2012, 3, 4) }); + testObj(obj); + assert.observableIsValid(testObj, obj); }); -test('Object is NOT Valid and isValid returns False and max is date', function () { - var obj = new Date(2013, 05, 04); - var testObj = ko.observable('') - .extend({ max: new Date(2012, 03, 04) }); - - testObj(obj); - - equal(testObj(), obj, 'observable still works'); - equal(testObj.isValid(), false, 'testObj is not valid'); +QUnit.test('Object is NOT Valid and isValid returns False and max is date', function(assert) { + var obj = new Date(2013, 5, 4); + var maxValue = new Date(2012, 3, 4); + var testObj = ko.observable('').extend({ max: maxValue }); + testObj(obj); + assert.violatesMaxRule(testObj, obj, maxValue); }); //#endregion //#region Min Length Validation -module('MinLength Validation'); - -test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { +QUnit.module('MinLength Validation'); +QUnit.test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ minLength: 2 }); - testObj(); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, undefined); }); -test('Object is Valid when null value is present - Preserves Optional Properties', function () { - +QUnit.test('Object is Valid when null value is present - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ minLength: 2 }); testObj(null); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, null); }); -test('Object is Valid when empty string is present - Preserves Optional Properties', function () { - +QUnit.test('Object is Valid when empty string is present - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ minLength: 2 }); testObj(''); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, ''); }); -test('Object is Valid when no value is present - Preserves Optional Properties', function () { - - var testObj = ko.observable().extend({ minLength: 2 }); - testObj(''); - ok(testObj.isValid(), 'testObj is Valid'); - -}); - -test('Object is Valid and isValid returns True', function () { - var testObj = ko.observable('') - .extend({ minLength: 5 }); - +QUnit.test('Object is Valid and isValid returns True', function(assert) { + var testObj = ko.observable('').extend({ minLength: 5 }); testObj('something'); - - equal(testObj(), 'something', 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, 'something'); }); -test('Object is NOT Valid and isValid returns False', function () { - var testObj = ko.observable('') - .extend({ minLength: 12 }); - +QUnit.test('Object is NOT Valid and isValid returns False', function(assert) { + var testObj = ko.observable('').extend({ minLength: 12 }); testObj('something'); - - equal(testObj(), 'something', 'observable still works'); - equal(testObj.isValid(), false, 'testObj is not valid'); + assert.violatesMinLengthRule(testObj, 'something', 12); }); -test('Issue #33 - Arrays - Valid', function () { - var testObj = ko.observableArray() - .extend({ minLength: 2 }); - - testObj(['one', 'two', 'three']); - ok(testObj.isValid(), 'testObj is Valid'); +QUnit.test('Issue #33 - Arrays - Valid', function(assert) { + var testObj = ko.observableArray().extend({ minLength: 2 }); + var obj = ['one', 'two', 'three']; + testObj(obj); + assert.observableIsValid(testObj, obj); }); -test('Issue #33 - Arrays - Invalid', function () { - var testObj = ko.observableArray() - .extend({ minLength: 4 }); - - testObj(['one', 'two', 'three']); - ok(!testObj.isValid(), testObj.error()); +QUnit.test('Issue #33 - Arrays - Invalid', function(assert) { + var testObj = ko.observableArray().extend({ minLength: 4 }); + var obj = ['one', 'two', 'three']; + testObj(obj); + assert.violatesMinLengthRule(testObj, obj, 4); }); -test('Object is Valid and minLength is observable and isValid returns True', function () { +QUnit.test('Object is Valid and minLength is observable and isValid returns True', function(assert) { var minLength = ko.observable(5); - var testObj = ko.observable('') - .extend({ minLength: minLength }); - + var testObj = ko.observable('').extend({ minLength: minLength }); testObj('something'); - - equal(testObj(), 'something', 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, 'something'); }); -test('Object is NOT Valid and minLength is observable and isValid returns False', function () { +QUnit.test('Object is NOT Valid and minLength is observable and isValid returns False', function(assert) { var minLength = ko.observable(12); - var testObj = ko.observable('') - .extend({ minLength: minLength }); - + var testObj = ko.observable('').extend({ minLength: minLength }); testObj('something'); - - equal(testObj(), 'something', 'observable still works'); - equal(testObj.isValid(), false, 'testObj is not valid'); + assert.violatesMinLengthRule(testObj, 'something', 12); }); -test('Issue #457 - Number is valid when digits are within applicable length', function () { +QUnit.test('Issue #457 - Number is valid when digits are within applicable length', function(assert) { var minLength = ko.observable(5); - var testObj = ko.observable('') - .extend({ minLength: minLength }); - + var testObj = ko.observable('').extend({ minLength: minLength }); testObj(12345); - - equal(testObj(), 12345, 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, 12345); }); -test('Issue #457 - Number is invalid when digits are outside of applicable length', function () { +QUnit.test('Issue #457 - Number is invalid when digits are outside of applicable length', function(assert) { var minLength = ko.observable(5); - var testObj = ko.observable('') - .extend({ minLength: minLength }); - + var testObj = ko.observable('').extend({ minLength: minLength }); testObj(1234); - - equal(testObj(), 1234, 'observable still works'); - ok(!testObj.isValid(), 'testObj is Valid'); + assert.violatesMinLengthRule(testObj, 1234, 5); }); + //#endregion //#region Max Length Validation -module('MaxLength Validation'); - -test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { +QUnit.module('MaxLength Validation'); +QUnit.test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ maxLength: 2 }); - testObj(); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, undefined); }); -test('Object is Valid when null value is present - Preserves Optional Properties', function () { - +QUnit.test('Object is Valid when null value is present - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ maxLength: 2 }); testObj(null); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, null); }); -test('Object is Valid when empty string is present - Preserves Optional Properties', function () { - +QUnit.test('Object is Valid when empty string is present - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ maxLength: 2 }); testObj(''); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, ''); }); -test('Object is Valid and isValid returns True', function () { - var testObj = ko.observable('') - .extend({ maxLength: 10 }); - +QUnit.test('Object is Valid and isValid returns True', function(assert) { + var testObj = ko.observable('').extend({ maxLength: 10 }); testObj('something'); - - equal(testObj(), 'something', 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, 'something'); }); -test('Object is NOT Valid and isValid returns False', function () { - var testObj = ko.observable('') - .extend({ maxLength: 6 }); - +QUnit.test('Object is NOT Valid and isValid returns False', function(assert) { + var testObj = ko.observable('').extend({ maxLength: 6 }); testObj('something'); - - equal(testObj(), 'something', 'observable still works'); - equal(testObj.isValid(), false, 'testObj is not valid'); + assert.violatesMaxLengthRule(testObj, 'something', 6); }); -test('Issue #33 - Arrays - Valid', function () { - var testObj = ko.observableArray() - .extend({ maxLength: 4 }); - - testObj(['one', 'two', 'three']); - ok(testObj.isValid(), 'testObj is Valid'); +QUnit.test('Issue #33 - Arrays - Valid', function(assert) { + var testObj = ko.observableArray().extend({ maxLength: 4 }); + var obj = ['one', 'two', 'three']; + testObj(obj); + assert.observableIsValid(testObj, obj); }); -test('Issue #33 - Arrays - Invalid', function () { - var testObj = ko.observableArray() - .extend({ maxLength: 2 }); - - testObj(['one', 'two', 'three']); - ok(!testObj.isValid(), testObj.error()); +QUnit.test('Issue #33 - Arrays - Invalid', function(assert) { + var testObj = ko.observableArray().extend({ maxLength: 2 }); + var obj = ['one', 'two', 'three']; + testObj(obj); + assert.violatesMaxLengthRule(testObj, obj, 2); }); -test('Object is Valid and maxLength is observable and isValid returns True', function () { +QUnit.test('Object is Valid and maxLength is observable and isValid returns True', function(assert) { var maxLength = ko.observable(20); - var testObj = ko.observable('') - .extend({ maxLength: maxLength }); - + var testObj = ko.observable('').extend({ maxLength: maxLength }); testObj('something'); - - equal(testObj(), 'something', 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, 'something'); }); -test('Object is NOT Valid and maxLength is observable and isValid returns False', function () { +QUnit.test('Object is NOT Valid and maxLength is observable and isValid returns False', function(assert) { var maxLength = ko.observable(3); - var testObj = ko.observable('') - .extend({ maxLength: maxLength }); - + var testObj = ko.observable('').extend({ maxLength: maxLength }); testObj('something'); - - equal(testObj(), 'something', 'observable still works'); - equal(testObj.isValid(), false, 'testObj is not valid'); + assert.violatesMaxLengthRule(testObj, 'something', 3); }); -test('Issue #457 - Number is valid when digits are within applicable length', function () { +QUnit.test('Issue #457 - Number is valid when digits are within applicable length', function(assert) { var maxLength = ko.observable(5); - var testObj = ko.observable('') - .extend({ maxLength: maxLength }); - + var testObj = ko.observable('').extend({ maxLength: maxLength }); testObj(1); - - equal(testObj(), 1, 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, 1); }); -test('Issue #457 - Number is invalid when digits are outside of applicable length', function () { +QUnit.test('Issue #457 - Number is invalid when digits are outside of applicable length', function(assert) { var maxLength = ko.observable(5); - var testObj = ko.observable('') - .extend({ maxLength: maxLength }); - + var testObj = ko.observable('').extend({ maxLength: maxLength }); testObj(123456); - - equal(testObj(), 123456, 'observable still works'); - ok(!testObj.isValid(), 'testObj is Valid'); + assert.violatesMaxLengthRule(testObj, 123456, 5); }); + //#endregion //#region Pattern Validation -module('Pattern Validation'); - -test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { +QUnit.module('Pattern Validation'); +QUnit.test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ pattern: 'test' }); - testObj(); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, undefined); }); -test('Object is Valid when null value is present - Preserves Optional Properties', function () { - +QUnit.test('Object is Valid when null value is present - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ pattern: 'test' }); testObj(null); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, null); }); -test('Object is Valid when empty string is present - Preserves Optional Properties', function () { - +QUnit.test('Object is Valid when empty string is present - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ pattern: 'test' }); testObj(''); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, ''); }); -test('Object is Valid and isValid returns True', function () { - var testObj = ko.observable('') - .extend({ pattern: 'some' }); - +QUnit.test('Object is Valid and isValid returns True', function(assert) { + var testObj = ko.observable('').extend({ pattern: 'some' }); testObj('something'); - - equal(testObj(), 'something', 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, 'something'); }); -test('Object is NOT Valid and isValid returns False', function () { +QUnit.test('Object is NOT Valid and isValid returns False', function(assert) { var testObj = ko.observable('') .extend({ pattern: 'none' }); testObj('something'); - equal(testObj(), 'something', 'observable still works'); - equal(testObj.isValid(), false, 'testObj is not valid'); + assert.equal(testObj(), 'something', 'observable still works'); + assert.equal(testObj.isValid(), false, 'testObj is not valid'); }); -test('Pattern validation matches numbers', function () { - var testObj = ko.observable('') - .extend({ pattern: '^12' }); - +QUnit.test('Pattern validation matches numbers', function(assert) { + var testObj = ko.observable('').extend({ pattern: '^12' }); testObj(123); - - equal(testObj(), 123, 'observable still works'); - equal(testObj.isValid(), true, 'testObj is valid'); + assert.observableIsValid(testObj, 123); }); -test('Pattern validation mismatches numbers', function () { - var testObj = ko.observable('') - .extend({ pattern: 'none' }); - +QUnit.test('Pattern validation mismatches numbers', function(assert) { + var testObj = ko.observable('').extend({ pattern: 'none' }); testObj(123); - - equal(testObj(), 123, 'observable still works'); - equal(testObj.isValid(), false, 'testObj is not valid'); + assert.violatesPatternRule(testObj, 123); }); -test('Pattern validation doesn\'t break with non-string values', function () { - var testObj = ko.observable('') - .extend({ pattern: '^$' }); +QUnit.test('Pattern validation does not break with non-string values', function(assert) { + assert.expect(1); + + var testObj = ko.observable('').extend({ pattern: '^$' }); testObj(12345); testObj.isValid(); @@ -586,663 +414,502 @@ test('Pattern validation doesn\'t break with non-string values', function () { testObj({}); testObj.isValid(); - expect(0); + assert.ok(true, 'all checks succeeded'); }); -test('Pattern validation matches numbers and pattern is observable', function () { +QUnit.test('Pattern validation matches numbers and pattern is observable', function(assert) { var pattern = ko.observable('^12'); - var testObj = ko.observable('') - .extend({ pattern: pattern }); - + var testObj = ko.observable('').extend({ pattern: pattern }); testObj(123); - - equal(testObj(), 123, 'observable still works'); - equal(testObj.isValid(), true, 'testObj is valid'); + assert.observableIsValid(testObj, 123); }); -test('Pattern validation mismatches numbers and pattern is observable', function () { +QUnit.test('Pattern validation mismatches numbers and pattern is observable', function(assert) { var pattern = ko.observable('none'); - var testObj = ko.observable('') - .extend({ pattern: 'none' }); - + var testObj = ko.observable('').extend({ pattern: pattern }); testObj(123); - - equal(testObj(), 123, 'observable still works'); - equal(testObj.isValid(), false, 'testObj is not valid'); + assert.violatesPatternRule(testObj, 123); }); + //#endregion //#region Step Validation -module('Step Validation'); - -test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { +QUnit.module('Step Validation'); +QUnit.test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ step: 2 }); - testObj(); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, undefined); }); -test('Object is Valid when null value is present - Preserves Optional Properties', function () { - +QUnit.test('Object is Valid when null value is present - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ step: 2 }); testObj(null); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, null); }); -test('Object is Valid when empty string is present - Preserves Optional Properties', function () { - +QUnit.test('Object is Valid when empty string is present - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ step: 2 }); testObj(''); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, ''); }); -test('Object is Valid and isValid returns True', function () { - var testObj = ko.observable('') - .extend({ step: 3 }); - +QUnit.test('Object is Valid and isValid returns True', function(assert) { + var testObj = ko.observable('').extend({ step: 3 }); testObj(6); - - equal(testObj(), 6, 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, 6); }); -test('Object is NOT Valid and isValid returns False', function () { - var testObj = ko.observable('') - .extend({ step: 2 }); - +QUnit.test('Object is NOT Valid and isValid returns False', function(assert) { + var testObj = ko.observable('').extend({ step: 2 }); testObj(5); - - equal(testObj(), 5, 'observable still works'); - equal(testObj.isValid(), false, 'testObj is not valid'); + assert.violatesStepRule(testObj, 5, 2); }); -test('Issue 74 - Object is Valid with a step of 0.1 and isValid returns True', function () { - var testObj = ko.observable('') - .extend({ step: 0.1 }); - +QUnit.test('Issue 74 - Object is Valid with a step of 0.1 and isValid returns True', function(assert) { + var testObj = ko.observable('').extend({ step: 0.1 }); testObj(6); - - equal(testObj(), 6, 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, 6); }); - -test('Issue 74 - Object is Valid with a step of 0.1 and incremented by 0.1 and isValid returns True', function () { - var testObj = ko.observable(6) - .extend({ step: 0.1 }); - +QUnit.test('Issue 74 - Object is Valid with a step of 0.1 and incremented by 0.1 and isValid returns True', function(assert) { + var testObj = ko.observable(6).extend({ step: 0.1 }); testObj(6.1); - - equal(testObj(), 6.1, 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, 6.1); }); -test('Issue 74 - Object is NOT Valid with a step of 0.1 and isValid returns False', function () { - var testObj = ko.observable('') - .extend({ step: 0.1 }); - +QUnit.test('Issue 74 - Object is NOT Valid with a step of 0.1 and isValid returns False', function(assert) { + var testObj = ko.observable('').extend({ step: 0.1 }); testObj(5); testObj(5.15); - - equal(testObj(), 5.15, 'observable still works'); - equal(testObj.isValid(), false, 'testObj is not valid'); + assert.violatesStepRule(testObj, 5.15, 0.1); }); -test('Step validation fix regression check', function () { +QUnit.test('Step validation fix regression check', function(assert) { var testObj = ko.observable(33.34).extend({ step: 0.01 }); - ok(!testObj.error(), 'step validation not triggered'); + assert.observableIsValid(testObj, 33.34); }); -test('Step validation any value is allowed', function () { +QUnit.test('Step validation any value is allowed', function(assert) { var testObj = ko.observable(33.34).extend({ step: 'any' }); - ok(!testObj.error(), '"any" value for step is allowed'); + assert.observableIsValid(testObj, 33.34); }); -test('Object is Valid and step is observable and isValid returns True', function () { +QUnit.test('Object is Valid and step is observable and isValid returns True', function(assert) { var step = ko.observable(3); - var testObj = ko.observable('') - .extend({ step: step }); - + var testObj = ko.observable('').extend({ step: step }); testObj(6); - - equal(testObj(), 6, 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, 6); }); -test('Object is NOT Valid and step is observable and isValid returns False', function () { +QUnit.test('Object is NOT Valid and step is observable and isValid returns False', function(assert) { var step = ko.observable(3); - var testObj = ko.observable('') - .extend({ step: step }); - + var testObj = ko.observable('').extend({ step: step }); testObj(5); - - equal(testObj(), 5, 'observable still works'); - equal(testObj.isValid(), false, 'testObj is not valid'); + assert.violatesStepRule(testObj, 5, 3); }); //#endregion //#region Email Validation -module('Email Validation'); - -test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { +QUnit.module('Email Validation'); +QUnit.test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ email: true }); - testObj(); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, undefined); }); -test('Object is Valid when null value is present - Preserves Optional Properties', function () { - +QUnit.test('Object is Valid when null value is present - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ email: true }); testObj(null); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, null); }); -test('Object is Valid when empty string is present - Preserves Optional Properties', function () { - +QUnit.test('Object is Valid when empty string is present - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ email: true }); testObj(''); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, ''); }); -test('Object is Valid and isValid returns True', function () { +QUnit.test('Object is Valid and isValid returns True', function(assert) { var testObj = ko.observable('').extend({ email: true }); - testObj('test@example.com'); - - equal(testObj(), 'test@example.com', 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, 'test@example.com'); }); -test('Object is NOT Valid and isValid returns False', function () { +QUnit.test('Object is NOT Valid and isValid returns False', function(assert) { var testObj = ko.observable('').extend({ email: true }); - testObj('text#example.com'); - - equal(testObj(), 'text#example.com', 'observable still works'); - equal(testObj.isValid(), false, testObj.error()); - equal(testObj.error(), 'Please enter a proper email address.', "Error Message Needs to be formatted correctly"); + assert.violatesEmailRule(testObj, 'text#example.com'); }); -test('Email with invalid domain', function () { +QUnit.test('Email with invalid domain', function(assert) { var testObj = ko.observable().extend({ email: true }); - - testObj("john@abc.com123"); - - equal(testObj.isValid(), false, testObj.error()); - equal(testObj.error(), 'Please enter a proper email address.'); + testObj('john@abc.com123'); + assert.violatesEmailRule(testObj, 'john@abc.com123'); }); -test('Object is Valid and email is observable and isValid returns True', function () { +QUnit.test('Object is Valid and email is observable and isValid returns True', function(assert) { var email = ko.observable(true); var testObj = ko.observable('').extend({ email: email }); - testObj('test@example.com'); - - equal(testObj(), 'test@example.com', 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, 'test@example.com'); }); -test('Object is NOT Valid and email is observable and isValid returns False', function () { +QUnit.test('Object is NOT Valid and email is observable and isValid returns False', function(assert) { var email = ko.observable(true); var testObj = ko.observable('').extend({ email: email }); - testObj('text#example.com'); - - equal(testObj(), 'text#example.com', 'observable still works'); - equal(testObj.isValid(), false, testObj.error()); - equal(testObj.error(), 'Please enter a proper email address.', "Error Message Needs to be formatted correctly"); + assert.violatesEmailRule(testObj, 'text#example.com'); }); + //#endregion //#region Date Validation -module('Date Validation'); - -test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { +QUnit.module('Date Validation'); +QUnit.test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ date: 'test' }); - testObj(); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, undefined); }); -test('Object is Valid when null value is present - Preserves Optional Properties', function () { - +QUnit.test('Object is Valid when null value is present - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ date: 'test' }); testObj(null); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, null); }); -test('Object is Valid when empty string is present - Preserves Optional Properties', function () { - +QUnit.test('Object is Valid when empty string is present - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ date: 'test' }); testObj(''); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, ''); }); -test('Object is Valid and isValid returns True', function () { +QUnit.test('Object is Valid and isValid returns True', function(assert) { var testObj = ko.observable('').extend({ date: true }); - testObj('11/18/2011'); - - equal(testObj(), '11/18/2011', 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, '11/18/2011'); }); -test('Object is NOT Valid and isValid returns False', function () { +QUnit.test('Object is NOT Valid and isValid returns False', function(assert) { var testObj = ko.observable('').extend({ date: true }); - testObj('stuff'); - - equal(testObj(), 'stuff', 'observable still works'); - equal(testObj.isValid(), false, testObj.error()); + assert.violatesDateRule(testObj, 'stuff'); }); -test('Object is Valid and date is observable and isValid returns True', function () { +QUnit.test('Object is Valid and date is observable and isValid returns True', function(assert) { var date = ko.observable(true); var testObj = ko.observable('').extend({ date: date }); - testObj('11/18/2011'); - - equal(testObj(), '11/18/2011', 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, '11/18/2011'); }); -test('Object is NOT Valid and isValid returns False', function () { +QUnit.test('Object is NOT Valid and isValid returns False', function(assert) { var date = ko.observable(true); var testObj = ko.observable('').extend({ date: date }); - testObj('stuff'); - - equal(testObj(), 'stuff', 'observable still works'); - equal(testObj.isValid(), false, testObj.error()); + assert.violatesDateRule(testObj, 'stuff'); }); //#endregion //#region DateISO Validation -module('DateISO Validation'); - -test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { +QUnit.module('DateISO Validation'); +QUnit.test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ dateISO: 'test' }); - testObj(); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, undefined); }); -test('Object is Valid when null value is present - Preserves Optional Properties', function () { - +QUnit.test('Object is Valid when null value is present - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ dateISO: 'test' }); testObj(null); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, null); }); -test('Object is Valid when empty string is present - Preserves Optional Properties', function () { - +QUnit.test('Object is Valid when empty string is present - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ dateISO: 'test' }); testObj(''); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, ''); }); -test('Object is Valid and isValid returns True', function () { +QUnit.test('Object is Valid and isValid returns True', function(assert) { var testObj = ko.observable('').extend({ dateISO: true }); - testObj('2011-11-18'); - - equal(testObj(), '2011-11-18', 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, '2011-11-18'); }); -test('Object is NOT Valid and isValid returns False', function () { +QUnit.test('Object is NOT Valid and isValid returns False', function(assert) { var testObj = ko.observable('').extend({ dateISO: true }); - testObj('stuff'); - - equal(testObj(), 'stuff', 'observable still works'); - equal(testObj.isValid(), false, testObj.error()); + assert.violatesDateRule(testObj, 'stuff'); }); -test('Object is Valid and dateISO is observable and isValid returns True', function () { +QUnit.test('Object is Valid and dateISO is observable and isValid returns True', function(assert) { var dateISO = ko.observable(true); var testObj = ko.observable('').extend({ dateISO: dateISO }); - testObj('2011-11-18'); - - equal(testObj(), '2011-11-18', 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, '2011-11-18'); }); -test('Object is NOT Valid and dateISO is observable and isValid returns False', function () { +QUnit.test('Object is NOT Valid and dateISO is observable and isValid returns False', function(assert) { var dateISO = ko.observable(true); var testObj = ko.observable('').extend({ dateISO: dateISO }); - testObj('stuff'); - - equal(testObj(), 'stuff', 'observable still works'); - equal(testObj.isValid(), false, testObj.error()); + assert.violatesDateRule(testObj, 'stuff'); }); -test('Object is NOT Valid if month is not in acceptable range', function() { +QUnit.test('Object is NOT Valid if month is not in acceptable range', function(assert) { var testObj = ko.observable('').extend({ dateISO: true }); - testObj('2011-13-18'); - - equal(testObj(), '2011-13-18', 'observable still works'); - equal(testObj.isValid(), false, testObj.error()); + assert.violatesDateRule(testObj, '2011-13-18'); }); -test('Object is NOT Valid if day is not in acceptable range', function() { +QUnit.test('Object is NOT Valid if day is not in acceptable range', function(assert) { var testObj = ko.observable('').extend({ dateISO: true }); - testObj('2011-12-40'); - - equal(testObj(), '2011-12-40', 'observable still works'); - equal(testObj.isValid(), false, testObj.error()); + assert.violatesDateRule(testObj, '2011-12-40'); }); //#endregion //#region Number Validation -module('Number Validation'); - -test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { +QUnit.module('Number Validation'); +QUnit.test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ number: true }); - testObj(); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, undefined); }); -test('Object is Valid when null value is present - Preserves Optional Properties', function () { - +QUnit.test('Object is Valid when null value is present - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ number: true }); testObj(null); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, null); }); -test('Object is Valid when empty string is present - Preserves Optional Properties', function () { - +QUnit.test('Object is Valid when empty string is present - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ number: true }); testObj(''); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, ''); }); -test('Object is Valid and isValid returns True', function () { +QUnit.test('Object is Valid and isValid returns True', function(assert) { var testObj = ko.observable('').extend({ number: true }); - testObj(200.01); - - equal(testObj(), 200.01, 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, 200.01); }); -test('Number is Valid (starting with point) and isValid returns True', function () { +QUnit.test('Number is Valid (starting with point) and isValid returns True', function(assert) { var testObj = ko.observable('').extend({ number: true }); - - testObj(".15"); - - equal(testObj(), ".15", 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + testObj('.15'); + assert.observableIsValid(testObj, '.15'); }); -test('Object is NOT Valid and isValid returns False', function () { +QUnit.test('Object is NOT Valid and isValid returns False', function(assert) { var testObj = ko.observable('').extend({ number: true }); - testObj('stuff'); - - equal(testObj(), 'stuff', 'observable still works'); - equal(testObj.isValid(), false, testObj.error()); + assert.violatesNumberRule(testObj, 'stuff'); }); -test('Number is Valid (starting with point) and number is observable and isValid returns True', function () { +QUnit.test('Number is Valid (starting with point) and number is observable and isValid returns True', function(assert) { var number = ko.observable(true); var testObj = ko.observable('').extend({ number: number }); - - testObj(".15"); - - equal(testObj(), ".15", 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + testObj('.15'); + assert.observableIsValid(testObj, '.15'); }); -test('Object is NOT Valid and number is observable and isValid returns False', function () { +QUnit.test('Object is NOT Valid and number is observable and isValid returns False', function(assert) { var number = ko.observable(true); var testObj = ko.observable('').extend({ number: number }); - testObj('stuff'); - - equal(testObj(), 'stuff', 'observable still works'); - equal(testObj.isValid(), false, testObj.error()); + assert.violatesNumberRule(testObj, 'stuff'); }); + //#endregion //#region Digit Validation -module('Digit Validation'); - -test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { +QUnit.module('Digit Validation'); +QUnit.test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ digit: true }); - testObj(); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, undefined); }); -test('Object is Valid when null value is present - Preserves Optional Properties', function () { - +QUnit.test('Object is Valid when null value is present - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ digit: true }); testObj(null); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, null); }); -test('Object is Valid when empty string is present - Preserves Optional Properties', function () { - +QUnit.test('Object is Valid when empty string is present - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ digit: true }); testObj(''); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, ''); }); -test('Object is Valid and isValid returns True', function () { +QUnit.test('Object is Valid and isValid returns True', function(assert) { var testObj = ko.observable('').extend({ digit: true }); - testObj(2); - - equal(testObj(), 2, 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, 2); }); -test('Object is NOT Valid and isValid returns False', function () { +QUnit.test('Object is NOT Valid and isValid returns False', function(assert) { var testObj = ko.observable('').extend({ digit: true }); - testObj('stuff'); - - equal(testObj(), 'stuff', 'observable still works'); - equal(testObj.isValid(), false, testObj.error()); + assert.violatesDigitRule(testObj, 'stuff'); }); -test('Object is Valid and digit is observable and isValid returns True', function () { +QUnit.test('Object is Valid and digit is observable and isValid returns True', function(assert) { var digit = ko.observable(true); var testObj = ko.observable('').extend({ digit: digit }); - testObj(2); - - equal(testObj(), 2, 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, 2); }); -test('Object is NOT Valid and digit is observable and isValid returns False', function () { +QUnit.test('Object is NOT Valid and digit is observable and isValid returns False', function(assert) { var digit = ko.observable(true); var testObj = ko.observable('').extend({ digit: digit }); - testObj('stuff'); - - equal(testObj(), 'stuff', 'observable still works'); - equal(testObj.isValid(), false, testObj.error()); + assert.violatesDigitRule(testObj, 'stuff'); }); //#endregion //#region PhoneUS Validation -module('PhoneUS Validation'); -test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function () { +QUnit.module('PhoneUS Validation'); +QUnit.test('Object is Valid when observable has not been initialized - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ phoneUS: true }); - testObj(); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, undefined); }); -test('Object is Valid when null value is present - Preserves Optional Properties', function () { - +QUnit.test('Object is Valid when null value is present - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ phoneUS: true }); testObj(null); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, null); }); -test('Object is Valid when empty string is present - Preserves Optional Properties', function () { - +QUnit.test('Object is Valid when empty string is present - Preserves Optional Properties', function(assert) { var testObj = ko.observable().extend({ phoneUS: true }); testObj(''); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, ''); }); -test('Object is Valid and isValid returns True', function () { +QUnit.test('Object is Valid and isValid returns True', function(assert) { var testObj = ko.observable('').extend({ phoneUS: true }); - testObj('765-523-4569'); - - equal(testObj(), '765-523-4569', 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, '765-523-4569'); }); -test('Object is NOT Valid and isValid returns False', function () { +QUnit.test('Object is NOT Valid and isValid returns False', function(assert) { var testObj = ko.observable('').extend({ phoneUS: true }); - testObj(5); - - equal(testObj(), 5, 'observable still works'); - equal(testObj.isValid(), false, 'testObj is not valid'); + assert.violatesPhoneUSRule(testObj, 5); }); -test('Object is Valid and phoneUS is observable and isValid returns True', function () { +QUnit.test('Object is Valid and phoneUS is observable and isValid returns True', function(assert) { var phoneUS = ko.observable(true); var testObj = ko.observable('').extend({ phoneUS: phoneUS }); - testObj('765-523-4569'); - - equal(testObj(), '765-523-4569', 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, '765-523-4569'); }); -test('Object is NOT Valid and phoneUS is observable and isValid returns False', function () { +QUnit.test('Object is NOT Valid and phoneUS is observable and isValid returns False', function(assert) { var phoneUS = ko.observable(true); var testObj = ko.observable('').extend({ phoneUS: phoneUS }); - testObj(5); - - equal(testObj(), 5, 'observable still works'); - equal(testObj.isValid(), false, 'testObj is not valid'); + assert.violatesPhoneUSRule(testObj, 5); }); + //#endregion //#region Equal tests -module("Equal Tests"); -test('Object is Valid and isValid returns True', function () { +QUnit.module('Equal Tests'); + +QUnit.test('Object is Valid and isValid returns True', function(assert) { var compareObj = ko.observable(12); var testObj = ko.observable('').extend({ equal: compareObj }); - testObj(12); - - equal(testObj(), 12, 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, 12); }); -test('Object is NOT Valid and isValid returns False', function () { +QUnit.test('Object is NOT Valid and isValid returns False', function(assert) { var compareObj = ko.observable(12); var testObj = ko.observable('').extend({ equal: compareObj }); - testObj(11); - - equal(testObj(), 11, 'observable still works'); - equal(testObj.isValid(), false, 'testObj is not valid'); + assert.violatesMustEqualRule(testObj, 11); }); //#endregion //#region NotEqual tests -module("Not Equal Tests"); -test('Object is Valid and isValid returns True', function () { +QUnit.module('Not Equal Tests'); + +QUnit.test('Object is Valid and isValid returns True', function(assert) { var compareObj = ko.observable(12); var testObj = ko.observable('').extend({ notEqual: compareObj }); - testObj(11); - - equal(testObj(), 11, 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, 11); }); -test('Object is NOT Valid and isValid returns False', function () { +QUnit.test('Object is NOT Valid and isValid returns False', function(assert) { var compareObj = ko.observable(12); var testObj = ko.observable('').extend({ notEqual: compareObj }); - testObj(12); - - equal(testObj(), 12, 'observable still works'); - equal(testObj.isValid(), false, 'testObj is not valid'); + assert.violatesNotEqualRule(testObj, 12); }); //#endregion //#region Unique tests -module("Unique Tests"); -test('Object is Valid and isValid returns True', function () { +QUnit.module('Unique Tests'); + +QUnit.test('Object is Valid and isValid returns True', function(assert) { var compareObj = ko.observableArray([11, 12, 13]); var testObj = ko.observable('').extend({ unique: { collection: compareObj } }); - testObj(11); - - equal(testObj(), 11, 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, 11); }); -test('Object is NOT Valid and isValid returns False', function () { +QUnit.test('Object is NOT Valid and isValid returns False', function(assert) { var compareObj = ko.observableArray([11, 12, 13, 13]); var testObj = ko.observable('').extend({ unique: { collection: compareObj } }); - testObj(13); - - equal(testObj(), 13, 'observable still works'); - equal(testObj.isValid(), false, 'testObj is not valid'); + assert.violatesUniqueRule(testObj, 13); }); -test('Correct unique validation behaviour for external values', function () { +QUnit.test('Correct unique validation behaviour for external values', function(assert) { var compareObj = ko.observableArray([11, 12, 13, 13]); var testObj = ko.observable('').extend({ unique: { collection: compareObj, externalValue: true } }); testObj(12); - equal(testObj.isValid(), false, 'testObj is not valid'); + assert.violatesUniqueRule(testObj, 12); testObj(13); - equal(testObj.isValid(), false, 'testObj is not valid'); + assert.violatesUniqueRule(testObj, 13); testObj(10); - equal(testObj.isValid(), true, 'testObj is valid'); + assert.observableIsValid(testObj, 10); }); -test('Issue #365 - Correct unique validation behaviour for external values that are in the collection', function () { +QUnit.test('Issue #365 - Correct unique validation behaviour for external values that are in the collection', function(assert) { var compareObj = ko.observableArray([11, 12, 13, 13]); var testObj = ko.observable('').extend({ unique: { collection: compareObj, externalValue: 12 } }); testObj(12); - equal(testObj.isValid(), false, 'testObj is not valid'); + assert.violatesUniqueRule(testObj, 12); testObj(10); - equal(testObj.isValid(), true, 'testObj is valid'); + assert.observableIsValid(testObj, 10); }); //#endregion diff --git a/Tests/test-runner.htm b/Tests/test-runner.htm index 7fe51f62..ca82f142 100644 --- a/Tests/test-runner.htm +++ b/Tests/test-runner.htm @@ -1,5 +1,5 @@ - - + + @@ -9,6 +9,7 @@ + @@ -36,8 +37,6 @@

      diff --git a/Tests/utils-tests.js b/Tests/utils-tests.js index 80959b89..8daab375 100644 --- a/Tests/utils-tests.js +++ b/Tests/utils-tests.js @@ -1,23 +1,11 @@ -/*global - module:false, - equal:false, - notEqual:false, - strictEqual:false, - deepEqual:false, - test:false, - ok:false, - asyncTest:false, - start: false, - stop: false, - expect: false -*/ +/*global QUnit:false*/ //#region Utils Tests -module("Utils tests"); +QUnit.module('Utils tests'); -test('Issue #31 - Recursively Show All Messages', function () { +QUnit.test('Issue #31 - Recursively Show All Messages', function(assert) { var vm = { one: ko.observable().extend({ required: true }), two: { @@ -32,21 +20,21 @@ test('Issue #31 - Recursively Show All Messages', function () { var errors = ko.validation.group(vm, { deep: true, observable: false }); - ok(!vm.one.isModified(), "Level 1 is not modified"); - ok(!vm.two.one.isModified(), "Level 2 is not modified"); - ok(!vm.three.two.one.isModified(), "Level 3 is not modified"); + assert.ok(!vm.one.isModified(), 'Level 1 is not modified'); + assert.ok(!vm.two.one.isModified(), 'Level 2 is not modified'); + assert.ok(!vm.three.two.one.isModified(), 'Level 3 is not modified'); // now show all the messages errors.showAllMessages(); - ok(vm.one.isModified(), "Level 1 is modified"); - ok(vm.two.one.isModified(), "Level 2 is modified"); - ok(vm.three.two.one.isModified(), "Level 3 is modified"); + assert.ok(vm.one.isModified(), 'Level 1 is modified'); + assert.ok(vm.two.one.isModified(), 'Level 2 is modified'); + assert.ok(vm.three.two.one.isModified(), 'Level 3 is modified'); - equal(errors().length, 3, 'Grouping correctly finds 3 invalid properties'); + assert.equal(errors().length, 3, 'Grouping correctly finds 3 invalid properties'); }); -test('Issue #31 - Recursively Show All Messages - using computed', function () { +QUnit.test('Issue #31 - Recursively Show All Messages - using computed', function(assert) { var vm = { one: ko.observable().extend({ required: true }), two: { @@ -61,21 +49,21 @@ test('Issue #31 - Recursively Show All Messages - using computed', function () { var errors = ko.validation.group(vm, { deep: true, observable: true }); - ok(!vm.one.isModified(), "Level 1 is not modified"); - ok(!vm.two.one.isModified(), "Level 2 is not modified"); - ok(!vm.three.two.one.isModified(), "Level 3 is not modified"); + assert.ok(!vm.one.isModified(), 'Level 1 is not modified'); + assert.ok(!vm.two.one.isModified(), 'Level 2 is not modified'); + assert.ok(!vm.three.two.one.isModified(), 'Level 3 is not modified'); // now show all the messages errors.showAllMessages(); - ok(vm.one.isModified(), "Level 1 is modified"); - ok(vm.two.one.isModified(), "Level 2 is modified"); - ok(vm.three.two.one.isModified(), "Level 3 is modified"); + assert.ok(vm.one.isModified(), 'Level 1 is modified'); + assert.ok(vm.two.one.isModified(), 'Level 2 is modified'); + assert.ok(vm.three.two.one.isModified(), 'Level 3 is modified'); - equal(errors().length, 3, 'Grouping correctly finds 3 invalid properties'); + assert.equal(errors().length, 3, 'Grouping correctly finds 3 invalid properties'); }); -test('Issue #37 - Toggle ShowAllMessages', function () { +QUnit.test('Issue #37 - Toggle ShowAllMessages', function(assert) { var vm = { one: ko.observable().extend({ required: true }), two: { @@ -90,28 +78,28 @@ test('Issue #37 - Toggle ShowAllMessages', function () { var errors = ko.validation.group(vm, { deep: true, observable: true }); - ok(!vm.one.isModified(), "Level 1 is not modified"); - ok(!vm.two.one.isModified(), "Level 2 is not modified"); - ok(!vm.three.two.one.isModified(), "Level 3 is not modified"); + assert.ok(!vm.one.isModified(), 'Level 1 is not modified'); + assert.ok(!vm.two.one.isModified(), 'Level 2 is not modified'); + assert.ok(!vm.three.two.one.isModified(), 'Level 3 is not modified'); // now show all the messages errors.showAllMessages(); - ok(vm.one.isModified(), "Level 1 is modified"); - ok(vm.two.one.isModified(), "Level 2 is modified"); - ok(vm.three.two.one.isModified(), "Level 3 is modified"); + assert.ok(vm.one.isModified(), 'Level 1 is modified'); + assert.ok(vm.two.one.isModified(), 'Level 2 is modified'); + assert.ok(vm.three.two.one.isModified(), 'Level 3 is modified'); - equal(errors().length, 3, 'Grouping correctly finds 3 invalid properties'); + assert.equal(errors().length, 3, 'Grouping correctly finds 3 invalid properties'); // now shut them off errors.showAllMessages(false); - ok(!vm.one.isModified(), "Level 1 is not modified"); - ok(!vm.two.one.isModified(), "Level 2 is not modified"); - ok(!vm.three.two.one.isModified(), "Level 3 is not modified"); + assert.ok(!vm.one.isModified(), 'Level 1 is not modified'); + assert.ok(!vm.two.one.isModified(), 'Level 2 is not modified'); + assert.ok(!vm.three.two.one.isModified(), 'Level 3 is not modified'); }); -test('Grouping options does not overwrite global configuration options', function () { - // we can not access the configuration therefore we test by observing the behavior +QUnit.test('Grouping options does not overwrite global configuration options', function(assert) { + // we cannot access the configuration therefore we test by observing the behavior // deep option is false per default; // that should not change the config @@ -126,22 +114,24 @@ test('Grouping options does not overwrite global configuration options', functio var errors = ko.validation.group(vm); - equal(errors().length, 1, 'Grouping finds one invalid object because deep option was not specified.'); + assert.equal(errors().length, 1, 'Grouping finds one invalid object because deep option was not specified.'); }); -test("Issue #235 - formatMessage should unwrap observable parameters", function () { - var observable = ko.observable("a value"); - var format = "Format message: {0}"; +QUnit.test('Issue #235 - formatMessage should unwrap observable parameters', function(assert) { + var observable = ko.observable('a value'); + var format = 'Format message: {0}'; var formatted = ko.validation.formatMessage(format, observable); - equal("Format message: a value", formatted, "Message should be formatted with the observable value"); - equal("a value", observable(), "Source observable should not be altered"); + assert.equal('Format message: a value', formatted, 'Message should be formatted with the observable value'); + assert.equal('a value', observable(), 'Source observable should not be altered'); - formatted = ko.validation.formatMessage(format, "a value"); - equal("Format message: a value", formatted, "Message should be formatted with the non-observable value"); + formatted = ko.validation.formatMessage(format, 'a value'); + assert.equal('Format message: a value', formatted, 'Message should be formatted with the non-observable value'); }); -test("Issue #313 - When recursivly iterating object tree with deep option", function () { +QUnit.test('Issue #313 - When recursively iterating object tree with deep option', function(assert) { + assert.expect(2); + var ViewModel = function () { this.required = ko.observable().extend({ required: true }); this.child = this; @@ -149,27 +139,28 @@ test("Issue #313 - When recursivly iterating object tree with deep option", func var errors = ko.validation.group(new ViewModel(), { observable: true, deep: true }); - ok(true, "It should not throw stack overflow"); - equal(errors().length, 1); + assert.ok(true, 'It should not throw stack overflow'); + assert.equal(errors().length, 1); }); -test("isValidatable returns false for undefined", function () { - equal(ko.validation.utils.isValidatable(), false); - equal(ko.validation.utils.isValidatable(null), false); - equal(ko.validation.utils.isValidatable(undefined), false); +QUnit.test('isValidatable returns false for undefined', function(assert) { + assert.equal(ko.validation.utils.isValidatable(), false); + assert.equal(ko.validation.utils.isValidatable(null), false); + assert.equal(ko.validation.utils.isValidatable(undefined), false); }); -test("isObservableArray returns true for observable arrays", function () { +QUnit.test('isObservableArray returns true for observable arrays', function(assert) { var obsArray = ko.observableArray(), observable = ko.observable(), plainObject = {}, plainArray = []; - ok(ko.validation.utils.isObservableArray(obsArray)); - ok(!ko.validation.utils.isObservableArray(observable)); - ok(!ko.validation.utils.isObservableArray(plainObject)); - ok(!ko.validation.utils.isObservableArray(plainArray)); - ok(!ko.validation.utils.isObservableArray(null)); - ok(!ko.validation.utils.isObservableArray(undefined)); + assert.ok(ko.validation.utils.isObservableArray(obsArray)); + assert.ok(!ko.validation.utils.isObservableArray(observable)); + assert.ok(!ko.validation.utils.isObservableArray(plainObject)); + assert.ok(!ko.validation.utils.isObservableArray(plainArray)); + assert.ok(!ko.validation.utils.isObservableArray(null)); + assert.ok(!ko.validation.utils.isObservableArray(undefined)); }); -//#endregion \ No newline at end of file + +//#endregion diff --git a/Tests/validation-tests.js b/Tests/validation-tests.js index 41da43c5..eb1e3945 100644 --- a/Tests/validation-tests.js +++ b/Tests/validation-tests.js @@ -1,21 +1,11 @@ -/*global - module:false, - equal:false, - notEqual:false, - strictEqual:false, - deepEqual:false, - test:false, - ok:false, - asyncTest:false, - start: false, - stop: false, - expect: false -*/ +/*global QUnit:false*/ + //#region Custom Rule Validation -module('Custom Rule Validation'); -test('Custom Rule Is Valid Test', function () { +QUnit.module('Custom Rule Validation'); + +QUnit.test('Custom Rule Is Valid Test', function(assert) { ko.validation.rules['mustEqual'] = { validator: function (val, otherVal) { return val === otherVal; @@ -24,17 +14,12 @@ test('Custom Rule Is Valid Test', function () { }; ko.validation.registerExtenders(); //make sure the new rule is registered - var testObj = ko.observable(4).extend({ mustEqual: 5 }); - testObj(5); - - equal(testObj(), 5, 'observable still works'); - equal(testObj.isValid(), true, 'testObj is valid'); + assert.observableIsValid(testObj, 5); }); -test('Custom Rule Is NOT Valid Test', function () { - +QUnit.test('Custom Rule Is NOT Valid Test', function(assert) { ko.validation.rules['mustEqual'] = { validator: function (val, otherVal) { return val === otherVal; @@ -43,17 +28,12 @@ test('Custom Rule Is NOT Valid Test', function () { }; ko.validation.registerExtenders(); //make sure the new rule is registered - var testObj = ko.observable(4).extend({ mustEqual: 5 }); - testObj(6); - - equal(testObj(), 6, 'observable still works'); - ok(testObj.error(), testObj.error()); - equal(testObj.isValid(), false, 'testObj is valid'); + assert.observableIsNotValid(testObj, 6, 'The field must equal 5'); }); -test('Custom Rule Is Valid Test and params is observable', function () { +QUnit.test('Custom Rule Is Valid Test and params is observable', function(assert) { var mustEqual = ko.observable(5); ko.validation.rules['mustEqual'] = { validator: function (val, otherVal) { @@ -63,16 +43,12 @@ test('Custom Rule Is Valid Test and params is observable', function () { }; ko.validation.registerExtenders(); //make sure the new rule is registered - var testObj = ko.observable(4).extend({ mustEqual: mustEqual }); - testObj(5); - - equal(testObj(), 5, 'observable still works'); - equal(testObj.isValid(), true, 'testObj is valid'); + assert.observableIsValid(testObj, 5); }); -test('Custom Rule Is NOT Valid Test and params is observable', function () { +QUnit.test('Custom Rule Is NOT Valid Test and params is observable', function(assert) { var mustEqual = ko.observable(5); ko.validation.rules['mustEqual'] = { validator: function (val, otherVal) { @@ -82,42 +58,34 @@ test('Custom Rule Is NOT Valid Test and params is observable', function () { }; ko.validation.registerExtenders(); //make sure the new rule is registered - var testObj = ko.observable(4).extend({ mustEqual: mustEqual }); - testObj(6); - - equal(testObj(), 6, 'observable still works'); - ok(testObj.error(), testObj.error()); - equal(testObj.isValid(), false, 'testObj is valid'); + assert.observableIsNotValid(testObj, 6, 'The field must equal 5'); }); //#endregion //#region Custom Validation Message -module('Custom Validation Message'); -test('Custom Message Correctly appears', function () { +QUnit.module('Custom Validation Message'); +QUnit.test('Custom Message Correctly appears', function(assert) { var testObj = ko.observable('something').extend({ required: { message: 'This Message is Special' } }); - testObj(''); - - equal(testObj(), '', 'observable still works'); - equal(testObj.isValid(), false, 'testObj is valid'); - equal(testObj.error(), 'This Message is Special', "Message appears correctly"); + assert.observableIsNotValid(testObj, '', 'This Message is Special'); }); //#endregion //#region Anonymous Rule Validation -module('Anonymous Rule Validation'); -test('Object is Valid and isValid returns True', function () { +QUnit.module('Anonymous Rule Validation'); + +QUnit.test('Object is Valid and isValid returns True', function(assert) { var testObj = ko.observable(3).extend({ validation: { validator: function (val, someOtherVal) { @@ -127,14 +95,11 @@ test('Object is Valid and isValid returns True', function () { params: 5 } }); - testObj(5); - - equal(testObj(), 5, 'observable still works'); - equal(testObj.isValid(), true, 'testObj is valid'); + assert.observableIsValid(testObj, 5); }); -test('Object is Valid and isValid returns True', function () { +QUnit.test('Object is NOT Valid and isValid returns False', function(assert) { var testObj = ko.observable(3).extend({ validation: { validator: function (val, someOtherVal) { @@ -144,40 +109,28 @@ test('Object is Valid and isValid returns True', function () { params: 5 } }); - testObj(4); - - equal(testObj(), 4, 'observable still works'); - equal(testObj.isValid(), false, 'testObj is valid'); - equal(testObj.error(), 'Must Equal 5', 'Error Message Matches'); + assert.observableIsNotValid(testObj, 4, 'Must Equal 5'); }); -test( 'Issue #81 - Dynamic messages', function () { - - var CustomRule = function () { +QUnit.test('Issue #81 - Dynamic messages', function(assert) { + var CustomRule = function() { var self = this; this.message = 'before'; this.params = 0; - this.validator = function ( val, params ) { + this.validator = function(/*val, params*/) { self.message = 'after'; - return false; }; }; - - var testObj = ko.observable( 3 ).extend( { - validation: new CustomRule() - }); - - testObj( 4 ); - - equal( testObj.isValid(), false, 'testObj is not valid' ); - equal( testObj.error(), 'after', 'testObj changes messages dynamically' ); + var testObj = ko.observable( 3 ).extend({validation: new CustomRule()}); + testObj(4); + assert.observableIsNotValid(testObj, 4, 'after'); }); -test('Object is Valid and params is observable and isValid returns True', function () { +QUnit.test('Object is Valid and params is observable and isValid returns True', function(assert) { var params = ko.observable(5); var testObj = ko.observable(3).extend({ validation: { @@ -188,14 +141,11 @@ test('Object is Valid and params is observable and isValid returns True', functi params: params } }); - testObj(5); - - equal(testObj(), 5, 'observable still works'); - equal(testObj.isValid(), true, 'testObj is valid'); + assert.observableIsValid(testObj, 5); }); -test('Object is Valid and params is observable isValid returns True', function () { +QUnit.test('Object is NOT Valid and params is observable isValid returns False', function(assert) { var params = ko.observable(5); var testObj = ko.observable(3).extend({ validation: { @@ -206,39 +156,28 @@ test('Object is Valid and params is observable isValid returns True', function ( params: params } }); - testObj(4); - - equal(testObj(), 4, 'observable still works'); - equal(testObj.isValid(), false, 'testObj is valid'); - equal(testObj.error(), 'Must Equal 5', 'Error Message Matches'); + assert.observableIsNotValid(testObj, 4, 'Must Equal 5'); }); -module('Complex Rule Validation'); -test('Object is Valid and isValid returns True', function () { +QUnit.module('Complex Rule Validation'); + +QUnit.test('Object is NOT Valid and isValid returns False', function(assert) { var testObj = ko.observable(); - testObj.extend({ required: true }) - .extend({ minLength: 2 }) - .extend({ pattern: { - message: 'It must contain some', - params: 'some' - } - }); + testObj.extend({required: true}) + .extend({minLength: 2}) + .extend({pattern: {message: 'It must contain some', params: 'some'}}); - ok(!testObj.isValid(), testObj.error()); - ok(testObj.error().indexOf('required') > -1, "required is first error"); + assert.violatesRequiredRule(testObj, undefined); testObj('s'); - ok(!testObj.isValid(), testObj.error()); - ok(testObj.error().indexOf('at least') > -1, "Minimum Length not met"); + assert.violatesMinLengthRule(testObj, 's', 2); testObj('som'); - ok(!testObj.isValid(), testObj.error()); - ok(testObj.error().indexOf('must contain') > -1, "Doesn't match required pattern"); - + assert.violatesPatternRule(testObj, 'som', 'It must contain some'); }); -test('Object is Valid and isValid returns True', function () { +QUnit.test('Object is Valid and isValid returns True', function(assert) { var testObj = ko.observable().extend({ required: true, minLength: 2, @@ -247,48 +186,34 @@ test('Object is Valid and isValid returns True', function () { params: 'some' } }); - - ok(!testObj.isValid(), testObj.error()); - ok(testObj.error().indexOf('required') > -1, "required is first error"); - - testObj('s'); - ok(!testObj.isValid(), testObj.error()); - ok(testObj.error().indexOf('at least') > -1, "Minimum Length not met"); - - testObj('som'); - ok(!testObj.isValid(), testObj.error()); - ok(testObj.error().indexOf('must contain') > -1, "Doesn't match required pattern"); - + testObj('awesome'); + assert.observableIsValid(testObj, 'awesome'); }); -test("Issue #47 - Validation chaining issue with required and email rules", function () { +QUnit.test('Issue #47 - Validation chaining issue with required and email rules', function(assert) { var testObj = ko.observable() .extend({ required: true }) .extend({ email: { message: 'Invalid email address.' } }); - ok(!testObj.isValid(), testObj.error()); - ok(testObj.error().indexOf('required') > -1, "required is first error"); + // First error should be set by required rule + assert.violatesRequiredRule(testObj, undefined); - testObj('s'); // an invalid email address - ok(!testObj.isValid(), testObj.error()); - ok(testObj.error().indexOf('Invalid email') > -1, "Email error is second error"); + // the second error should be set by email rule (now that the observable has some text) + testObj('s'); + assert.observableIsNotValid(testObj, 's', 'Invalid email address.'); }); -test("Issue #43 - Error messages are not switched correctly", function () { +QUnit.test('Issue #43 - Error messages are not switched correctly', function(assert) { var testObj = ko.observable().extend({ min: 1, max: 100 }); testObj(-1); // should invalidate the min rule - - ok(!testObj.isValid(), testObj.error()); - ok(testObj.error().indexOf('enter a value greater than') > -1, "Min rule was correctly triggered"); + assert.violatesMinRule(testObj, -1, 1); testObj(101); // should invalidate the max rule - - ok(!testObj.isValid(), testObj.error()); - ok(testObj.error().indexOf('enter a value less than') > -1, "Max rule was correctly triggered"); + assert.violatesMaxRule(testObj, 101, 100); }); -test("Issue #43 - Grouping - Error messages are not switched correctly", function () { +QUnit.test('Issue #43 - Grouping - Error messages are not switched correctly', function(assert) { var vm = { testObj : ko.observable().extend({ min: 1, max: 100 }), dummyProp : ko.observable().extend({ required: true }) @@ -297,17 +222,13 @@ test("Issue #43 - Grouping - Error messages are not switched correctly", functio vm.errors = ko.validation.group(vm); vm.testObj(-1); // should invalidate the min rule - - ok(!vm.testObj.isValid(), vm.testObj.error()); - ok(vm.testObj.error().indexOf('enter a value greater than') > -1, "Min rule was correctly triggered"); + assert.violatesMinRule(vm.testObj, -1, 1); vm.testObj(101); // should invalidate the max rule - - ok(!vm.testObj.isValid(), vm.testObj.error()); - ok(vm.testObj.error().indexOf('enter a value less than') > -1, "Max rule was correctly triggered"); + assert.violatesMaxRule(vm.testObj, 101, 100); }); -test('Issue #78 - Falsy Params', function () { +QUnit.test('Issue #78 - Falsy Params', function(assert) { var testObj = ko.observable('') .extend({ min: { @@ -317,21 +238,19 @@ test('Issue #78 - Falsy Params', function () { }); testObj(1); - - equal(testObj(), 1, 'observable still works'); - equal(testObj.isValid(), true, 'testObj is valid'); + assert.observableIsValid(testObj, 1); testObj(0); - equal(testObj.isValid(), true, 'testObj is valid'); + assert.observableIsValid(testObj, 0); testObj(-1); - equal(testObj.isValid(), false, 'testObj is not valid'); - + assert.observableIsNotValid(testObj, -1, 'something'); }); -test("Issue 374 - onlyIf ignored", function () { +QUnit.test('Issue 374 - onlyIf ignored', function(assert) { var observable = ko.observable(), validationEnabled = ko.observable(true); + observable.extend({ validation: { validator: function () { return false; }, //always fail validation @@ -339,56 +258,63 @@ test("Issue 374 - onlyIf ignored", function () { } }); - ok(!observable.isValid(), "Should be validating as onlyIf returns true"); - validationEnabled(false); - ok(observable.isValid(), "Validation should now be disabled"); + // Should be validating as onlyIf returns true + assert.observableIsNotValid(observable, undefined, 'Error'); + + // Validation should now be disabled + validationEnabled(false); + assert.observableIsValid(observable, undefined); }); //#endregion //#region Conditional Validation -module('Conditional Validation in a rule'); -test('isValid always returns True when onlyIf Condition evaluates to false', function () { + +QUnit.module('Conditional Validation in a rule'); + +QUnit.test('isValid always returns True when onlyIf Condition evaluates to false', function(assert) { var testObj = ko.observable('something').extend({ required: { onlyIf: function() { return false; } } }); testObj(''); - equal(testObj(), '', 'observable still works'); - ok(testObj.isValid(), 'testObj is Valid'); + assert.observableIsValid(testObj, ''); }); -test('isValid returns False When onlyIf Condition evaluates to true and Value is invalid', function () { +QUnit.test('isValid returns False When onlyIf Condition evaluates to true and Value is invalid', function(assert) { var testObj = ko.observable('something').extend({ required: { onlyIf: function() { return true; } } }); testObj(''); - equal(testObj(), '', 'observable still works'); - equal(testObj.isValid(), false, 'testObj is not Valid'); + assert.violatesRequiredRule(testObj, ''); }); -test('Changing the value of observable used in onlyIf condition triggers validation', function () { +QUnit.test('Changing the value of observable used in onlyIf condition triggers validation', function(assert) { var person = { - isMarried: ko.observable(false).extend({ required: true }), + isMarried: ko.observable(false).extend({ required: true }) }; person.spouseName = ko.observable('').extend({ required: { onlyIf: person.isMarried } }); person.isMarried(false); - ok(person.spouseName.isValid(), 'Unmarried person is valid without spouse name'); + assert.observableIsValid(person.spouseName, ''); person.isMarried(true); - equal(person.spouseName.isValid(), false, 'Married person is not valid without spouse name'); + assert.violatesRequiredRule(person.spouseName, ''); }); + //#endregion //#region Async Tests -module('Async Tests'); -asyncTest('Async Rule Is Valid Test', function () { +QUnit.module('Async Tests'); + +QUnit.test('Async Rule Is Valid Test', function(assert) { + var done = assert.async(); + assert.expect(2); ko.validation.rules['mustEqualAsync'] = { async: true, @@ -396,9 +322,9 @@ asyncTest('Async Rule Is Valid Test', function () { var isValid = (val === otherVal); setTimeout(function () { callBack(isValid); - doAssertions(); - - start(); + assert.equal(testObj(), 5, 'observable still works'); + assert.equal(testObj.isValid(), true, 'testObj is valid'); + done(); }, 10); }, message: 'The field must equal {0}' @@ -406,49 +332,42 @@ asyncTest('Async Rule Is Valid Test', function () { ko.validation.registerExtenders(); //make sure the new rule is registered var testObj = ko.observable(5); - - var doAssertions = function () { - equal(testObj(), 5, 'observable still works'); - equal(testObj.isValid(), true, 'testObj is valid'); - }; - testObj.extend({ mustEqualAsync: 5 }); }); -asyncTest('Async Rule Is NOT Valid Test', function () { +QUnit.test('Async Rule Is NOT Valid Test', function(assert) { + var done = assert.async(); + assert.expect(3); ko.validation.rules['mustEqualAsync'] = { async: true, validator: function (val, otherVal, callBack) { var isValid = (val === otherVal); - setTimeout(function () { + setTimeout(function() { callBack(isValid); - doAssertions(); - start(); + assert.equal(testObj(), 4, 'observable still works'); + assert.ok(testObj.error(), 'The field must equal 5', testObj.error()); + assert.equal(testObj.isValid(), false, 'testObj is not valid'); + + done(); }, 10); }, message: 'The field must equal {0}' }; ko.validation.registerExtenders(); //make sure the new rule is registered - var testObj = ko.observable(4); - - var doAssertions = function () { - equal(testObj(), 4, 'observable still works'); - ok(testObj.error(), testObj.error()); - equal(testObj.isValid(), false, 'testObj is not valid'); - }; - testObj.extend({ mustEqualAsync: 5 }); }); + //#endregion //#region Message Formatting -module("Message formatting"); -test("message parameter receives params and observable", function () { +QUnit.module('Message formatting'); + +QUnit.test('message parameter receives params and observable', function(assert) { var testObj = ko.observable(3); testObj.extend({ validation: { @@ -456,34 +375,37 @@ test("message parameter receives params and observable", function () { return val === someOtherVal; }, message: function(params, observable) { - equal(testObj, observable, "The failing observable should be passed to the message function"); + assert.equal(testObj, observable, 'The failing observable should be passed to the message function'); - return "Must equal " + params; + return 'Must equal ' + params; }, params: 5 } }); - equal(testObj.error(), "Must equal 5", "The message function was not invoked"); + assert.equal(testObj.error(), 'Must equal 5', 'The message function was not invoked'); }); -asyncTest("message parameter receives params and observable when async", function () { +QUnit.test('message parameter receives params and observable when async', function(assert) { + var done = assert.async(); + assert.expect(2); + var testObj = ko.observable(4); ko.validation.rules['mustEqualAsync'] = { async: true, validator: function (val, otherVal, callBack) { var isValid = (val === otherVal); - setTimeout(function () { + setTimeout(function() { callBack(isValid); }, 10); }, message: function (params, observable) { - equal(observable, testObj, "The failing observable should be passed to the message function"); - equal(params, 5, "The params should be passed to the message function"); + assert.equal(observable, testObj, 'The failing observable should be passed to the message function'); + assert.equal(params, 5, 'The params should be passed to the message function'); + done(); - start(); - return "message"; + return 'message'; } }; ko.validation.registerExtenders(); //make sure the new rule is registered diff --git a/Tests/validation-ui-tests.js b/Tests/validation-ui-tests.js index 180117c8..01845324 100644 --- a/Tests/validation-ui-tests.js +++ b/Tests/validation-ui-tests.js @@ -1,57 +1,44 @@ -/*global - module:false, - equal:false, - notEqual:false, - strictEqual:false, - test:false, - ok:false, - asyncTest:false, - start: false, - stop: false, - $: false, - expect: false -*/ - -module('UI Tests', { - setup: function () { - - }, - teardown: function () { - ko.cleanNode($('#testContainer')[0]); - $('#testContainer').empty(); +/*global QUnit:false, $:false*/ + + +QUnit.module('UI Tests', { + afterEach: function() { + var $element = $('#testContainer'); + ko.cleanNode($element[0]); + $element.empty(); ko.validation.reset(); } }); //utility functions -var applyTestBindings = function (vm) { +var applyTestBindings = function(vm) { ko.applyBindingsWithValidation(vm, $('#testContainer')[0]); }; -var addTestHtml = function(html){ +var addTestHtml = function(html) { $('#testContainer').html(html); }; -test('hasAttribute works in old IE', function () { - addTestHtml(''); +QUnit.test('hasAttribute works in old IE', function(assert) { - var el = document.getElementById('myTestInput'); + addTestHtml(''); - ok(el, 'found element'); + var el = $('#myTestInput')[0]; - ok(ko.validation.utils.hasAttribute(el, 'required'), 'element correctly has html5 input attribute'); - ok(!ko.validation.utils.hasAttribute(el, 'pattern'), 'element correctly does not have html5 input attribute'); + assert.ok(el, 'found element'); + assert.ok(ko.validation.utils.hasAttribute(el, 'required'), 'element correctly has html5 input attribute'); + assert.ok(!ko.validation.utils.hasAttribute(el, 'pattern'), 'element correctly does not have html5 input attribute'); }); -test("checked binding sets error class on radio buttons", function() { +QUnit.test('checked binding sets error class on radio buttons', function(assert) { addTestHtml("" + "" + ""); - var $input = $("#testInput2"), + var $input = $('#testInput2'), vm = { - result: ko.observable("").extend({ required: true }) + result: ko.observable('').extend({ required: true }) }; ko.validation.init({ decorateInputElement: true }, true); @@ -59,21 +46,21 @@ test("checked binding sets error class on radio buttons", function() { applyTestBindings(vm); - ok(!vm.result.isValid(), "Should initially be invalid"); - ok($input.hasClass("validationElement"), "Validation class should have been added"); + assert.ok(!vm.result.isValid(), 'Should initially be invalid'); + assert.ok($input.hasClass('validationElement'), 'Validation class should have been added'); - $input.prop("checked", true); + $input.prop('checked', true); $input.click(); //trigger the validation - equal(vm.result(), "two", "Value should have changed"); - ok(vm.result.isValid(), "Should now be valid"); - ok(!$input.hasClass("validationElement"), "Validation class should have been removed"); + assert.equal(vm.result(), 'two', 'Value should have changed'); + assert.ok(vm.result.isValid(), 'Should now be valid'); + assert.ok(!$input.hasClass('validationElement'), 'Validation class should have been removed'); }); -test('textInput Binding Works', function () { +QUnit.test('textInput Binding Works', function(assert) { if (!ko.bindingHandlers.textInput) { // 'textInput binding not supported (ko.version < 3.2). - ok(true, 'ignore test'); + assert.ok(true, 'textInput binding is available in ko >= 3.2. The test will be skipped.'); return; } addTestHtml(''); @@ -86,20 +73,20 @@ test('textInput Binding Works', function () { var $testInput = $('#myTestInput'); - $testInput.val("a"); //set it + $testInput.val('a'); //set it $testInput.change(); //trigger change event - ok(vm.firstName.isValid(), 'First Name is Valid'); + assert.ok(vm.firstName.isValid(), 'First Name is Valid'); - $testInput.val(""); //set it + $testInput.val(''); //set it $testInput.change(); //trigger change event - ok(!vm.firstName.isValid(), 'First Name is NOT Valid'); + assert.ok(!vm.firstName.isValid(), 'First Name is NOT Valid'); var msg = $testInput.siblings().first().text(); - equal(msg, 'This field is required.', msg); + assert.equal(msg, 'This field is required.', msg); }); -test('selectedOptions Binding Works', function () { +QUnit.test('selectedOptions Binding Works', function(assert) { addTestHtml(''); @@ -126,19 +113,19 @@ test('selectedOptions Binding Works', function () { $testInput.val('First'); $testInput.change(); - ok(vm.selectedNames.isValid(), 'selectedNames is Valid'); + assert.ok(vm.selectedNames.isValid(), 'selectedNames is Valid'); $testInput.val(''); $testInput.change(); - ok(!vm.selectedNames.isValid(), 'selectedNames is NOT Valid'); + assert.ok(!vm.selectedNames.isValid(), 'selectedNames is NOT Valid'); var msg = $testInput.siblings().first().text(); - equal(msg, 'Please select at least one item.', msg); + assert.equal(msg, 'Please select at least one item.', msg); }); //#region Inserting Messages -test('Inserting Messages Works', function () { +QUnit.test('Inserting Messages Works', function(assert) { addTestHtml(''); @@ -148,24 +135,14 @@ test('Inserting Messages Works', function () { applyTestBindings(vm); - var $testInput = $('#myTestInput'); - - $testInput.val("a"); //set it - $testInput.change(); //trigger change event - - $testInput.val(""); //set it - $testInput.change(); //trigger change event - - var isValid = vm.firstName.isValid(); - - ok(!isValid, 'First Name is NOT Valid'); + var $testInput = $('#myTestInput').val('a').change().val('').change(); + assert.ok(!vm.firstName.isValid(), 'First Name is NOT Valid'); var msg = $testInput.siblings().first().text(); - - equal(msg, 'This field is required.', msg); + assert.equal(msg, 'This field is required.', msg); }); -test('Inserting Messages with HTML Works', function () { +QUnit.test('Inserting Messages with HTML Works', function(assert) { ko.validation.init({ allowHtmlMessages: true @@ -179,28 +156,18 @@ test('Inserting Messages with HTML Works', function () { applyTestBindings(vm); - var $testInput = $('#myTestInput'); - - $testInput.val("a"); //set it - $testInput.change(); //trigger change event - - $testInput.val(""); //set it - $testInput.change(); //trigger change event - - var isValid = vm.firstName.isValid(); - - ok(!isValid, 'First Name is NOT Valid'); + var $testInput = $('#myTestInput').val('a').change().val('').change(); + assert.ok(!vm.firstName.isValid(), 'First Name is NOT Valid'); var msg = $testInput.siblings().first().html(); - - equal(msg, 'This field is required.', msg); + assert.equal(msg, 'This field is required.', msg); }); //#endregion //#region Decorating Elements -test('Decorating Elements Works', function () { +QUnit.test('Decorating Elements Works', function(assert) { addTestHtml(''); @@ -216,19 +183,13 @@ test('Decorating Elements Works', function () { applyTestBindings(vm); var $testInput = $('#myTestInput'); + assert.ok(!$testInput.hasClass('validationElement'), "CSS class shouldn't present"); - ok(!$testInput.hasClass('validationElement'), "CSS class shouldn't present"); - - $testInput.val("a"); //set it - $testInput.change(); //trigger change event - - $testInput.val(""); //set it - $testInput.change(); //trigger change event - - ok($testInput.hasClass('validationElement'), "CSS class should present"); + $testInput.val('a').change().val('').change(); + assert.ok($testInput.hasClass('validationElement'), 'CSS class should present'); }); -test('Decorating Elements On Modified Works', function () { +QUnit.test('Decorating Elements On Modified Works', function(assert) { addTestHtml(''); @@ -246,19 +207,19 @@ test('Decorating Elements On Modified Works', function () { var $testInput = $('#myTestInput'); - ok($testInput.hasClass('validationElement'), "CSS class should present"); + assert.ok($testInput.hasClass('validationElement'), 'CSS class should present'); - $testInput.val("a"); //set it + $testInput.val('a'); //set it $testInput.change(); //trigger change event - ok(!$testInput.hasClass('validationElement'), "CSS class shouldn't present"); + assert.ok(!$testInput.hasClass('validationElement'), "CSS class shouldn't present"); }); //#endregion //#region Showing errors as titles -test('Showing Errors As Titles Works', function () { +QUnit.test('Showing Errors As Titles Works', function(assert) { addTestHtml(''); @@ -276,22 +237,22 @@ test('Showing Errors As Titles Works', function () { var $testInput = $('#myTestInput'); - $testInput.val("a"); //set it + $testInput.val('a'); //set it $testInput.change(); //trigger change event - $testInput.val(""); //set it + $testInput.val(''); //set it $testInput.change(); //trigger change event var isValid = vm.firstName.isValid(); - ok(!isValid, 'First Name is NOT Valid'); + assert.ok(!isValid, 'First Name is NOT Valid'); var msg = $testInput.attr('title'); - equal(msg, 'This field is required.', msg); + assert.equal(msg, 'This field is required.', msg); }); -test('Original titles are restored', function () { +QUnit.test('Original titles are restored', function(assert) { addTestHtml(''); @@ -309,24 +270,24 @@ test('Original titles are restored', function () { var $testInput = $('#myTestInput'); - $testInput.val("a"); //set it + $testInput.val('a'); //set it $testInput.change(); //trigger change event - $testInput.val(""); //set it + $testInput.val(''); //set it $testInput.change(); //trigger change event var msg = $testInput.attr('title'); - equal(msg, 'This field is required.', msg); + assert.equal(msg, 'This field is required.', msg); - $testInput.val("a"); //set it + $testInput.val('a'); //set it $testInput.change(); //trigger change event msg = $testInput.attr('title'); - equal(msg, 'my-orig-title', msg); + assert.equal(msg, 'my-orig-title', msg); }); -test("Original titles are restored to blank", function () { +QUnit.test('Original titles are restored to blank', function(assert) { addTestHtml(''); var vm = { @@ -343,24 +304,24 @@ test("Original titles are restored to blank", function () { var $testInput = $('#myTestInput'); - $testInput.val("a"); //set it + $testInput.val('a'); //set it $testInput.change(); //trigger change event - $testInput.val(""); //set it + $testInput.val(''); //set it $testInput.change(); //trigger change event - ok(!vm.firstName.isValid(), 'First Name is NOT Valid'); + assert.ok(!vm.firstName.isValid(), 'First Name is NOT Valid'); //now make the name valid - vm.firstName("valid name"); - ok(vm.firstName.isValid(), "Should now be valid"); + vm.firstName('valid name'); + assert.ok(vm.firstName.isValid(), 'Should now be valid'); //and check that the title was reset to blank - var updatedTitle = $testInput.attr("title"); - ok(!updatedTitle, "Title should have been reset to blank"); + var updatedTitle = $testInput.attr('title'); + assert.ok(!updatedTitle, 'Title should have been reset to blank'); }); -test('Original titles are restored with multiple validators, too', function () { +QUnit.test('Original titles are restored with multiple validators, too', function(assert) { addTestHtml(''); @@ -378,30 +339,30 @@ test('Original titles are restored with multiple validators, too', function () { var $testInput = $('#myTestInput'); - $testInput.val("aa"); //set it + $testInput.val('aa'); //set it $testInput.change(); //trigger change event - $testInput.val(""); //set it + $testInput.val(''); //set it $testInput.change(); //trigger change event var msg = $testInput.attr('title'); - equal(msg, 'This field is required.', msg); + assert.equal(msg, 'This field is required.', msg); - $testInput.val("a"); //set it + $testInput.val('a'); //set it $testInput.change(); //trigger change event msg = $testInput.attr('title'); - equal(msg, 'Please enter at least 2 characters.', msg); + assert.equal(msg, 'Please enter at least 2 characters.', msg); - $testInput.val("aa"); //set it + $testInput.val('aa'); //set it $testInput.change(); //trigger change event msg = $testInput.attr('title'); - equal(msg, 'my-orig-title', msg); + assert.equal(msg, 'my-orig-title', msg); }); -test('Showing Errors As Titles is disabled sucessfully', function () { +QUnit.test('Showing Errors As Titles is disabled successfully', function(assert) { addTestHtml(''); @@ -420,23 +381,22 @@ test('Showing Errors As Titles is disabled sucessfully', function () { var $testInput = $('#myTestInput'); - $testInput.val("a"); //set it + $testInput.val('a'); //set it $testInput.change(); //trigger change event - $testInput.val(""); //set it + $testInput.val(''); //set it $testInput.change(); //trigger change event var isValid = vm.firstName.isValid(); - ok(!isValid, 'First Name is NOT Valid'); + assert.ok(!isValid, 'First Name is NOT Valid'); var msg = $testInput.attr('title'); - notEqual(msg, 'This field is required.', msg); + assert.notEqual(msg, 'This field is required.', msg); }); -test("Removing error message from title when isModified is reset", function () { - +QUnit.test('Removing error message from title when isModified is reset', function(assert) { addTestHtml(''); var vm = { @@ -452,20 +412,18 @@ test("Removing error message from title when isModified is reset", function () { applyTestBindings(vm); - vm.prop("valid").prop(""); + vm.prop('valid').prop(''); vm.prop.isModified(false); - ok(!$("#myTestInput").attr("title")); + assert.ok(!$('#myTestInput').attr('title')); }); //#endregion //#region Validation Option Tests -test('Validation Options - Basic Tests', function () { - +QUnit.test('Validation Options - Basic Tests', function(assert) { var testHtml = '
      '; - addTestHtml(testHtml); var vm = { @@ -474,25 +432,17 @@ test('Validation Options - Basic Tests', function () { applyTestBindings(vm); - var $testInput = $('#myTestInput'); + var $testInput = $('#myTestInput') + .val('a').change() + .val('').change(); - $testInput.val("a"); //set it - $testInput.change(); //trigger change event - - $testInput.val(""); //set it - $testInput.change(); //trigger change event - - var isValid = vm.firstName.isValid(); - - ok(!isValid, 'First Name is NOT Valid'); + assert.violatesRequiredRule(vm.firstName, ''); var noMsgs = $testInput.siblings().length; - - equal(noMsgs, 0, 'No Messages were inserted'); - + assert.equal(noMsgs, 0, 'No Messages were inserted'); }); -test('Validation Options - Nested Test', function () { +QUnit.test('Validation Options - Nested Test', function(assert) { var testHtml = '
      ' + '' + @@ -512,24 +462,15 @@ test('Validation Options - Nested Test', function () { applyTestBindings(vm); - var $testInput = $('#myLastName'); - - $testInput.val("a"); //set it - $testInput.change(); //trigger change event - - var isValid = vm.someObj.lastName.isValid(); - - ok(!isValid, 'Last Name is NOT Valid'); + var $testInput = $('#myLastName').val('a').change(); + assert.violatesMinLengthRule(vm.someObj.lastName, 'a', 2); var noMsgs = $testInput.siblings().length; - - equal(noMsgs, 0, 'No Messages were inserted'); - + assert.equal(noMsgs, 0, 'No Messages were inserted'); }); -test('Validation Options - Options only apply to their HTML Contexts', function () { - - var testHtml = '
      ' + +QUnit.test('Validation Options - Options only apply to their HTML Contexts', function(assert) { + var testHtml = '
      ' + '
      ' + '
      ' + '' + @@ -537,7 +478,6 @@ test('Validation Options - Options only apply to their HTML Contexts', function '
      ' + '' + '
      '; - addTestHtml(testHtml); var vm = { @@ -549,31 +489,20 @@ test('Validation Options - Options only apply to their HTML Contexts', function applyTestBindings(vm); - var $testInput = $('#myLastName'); - - $testInput.val("a"); //set it - $testInput.change(); //trigger change event - - var isValid = vm.someObj.lastName.isValid(); - - ok(!isValid, 'Last Name is NOT Valid'); + var $testInput = $('#myLastName').val('a').change(); + assert.violatesMinLengthRule(vm.someObj.lastName, 'a', 2); var noMsgs = $testInput.siblings().length; + assert.equal(noMsgs, 0, 'No Messages were inserted'); - equal(noMsgs, 0, 'No Messages were inserted'); - - var $firstName = $('#myFirstName'); - $firstName.val(""); //set it - $firstName.change(); //trigger change event - - ok(!vm.firstName.isValid(), 'Validation Still works correctly'); + var $firstName = $('#myFirstName').val('').change(); + assert.violatesRequiredRule(vm.firstName, ''); var insertMsgCt = $firstName.siblings('span').length; - equal(insertMsgCt, 1, 'Should have inserted 1 message beside the first name!'); - + assert.equal(insertMsgCt, 1, 'Should have inserted 1 message beside the first name!'); }); -test("Issue #43 & #47 - Error messages are not switched correctly", function () { +QUnit.test('Issue #43 & #47 - Error messages are not switched correctly', function(assert) { var vm = { testObj: ko.observable().extend({ min: 1, max: 100 }), dummyProp: ko.observable().extend({ required: true }) @@ -588,17 +517,15 @@ test("Issue #43 & #47 - Error messages are not switched correctly", function () var $msg = $('#testMessage'); vm.testObj(-1); // should invalidate the min rule - - ok(!vm.testObj.isValid(), vm.testObj.error()); - equal(vm.testObj.error(), $msg.text(), "Min rule was correctly triggered"); + assert.violatesMinRule(vm.testObj, -1, 1); + assert.equal(vm.testObj.error(), $msg.text(), 'Min rule was correctly triggered'); vm.testObj(101); // should invalidate the max rule - - ok(!vm.testObj.isValid(), vm.testObj.error()); - equal(vm.testObj.error(), $msg.text(), "Max rule was correctly triggered"); + assert.violatesMaxRule(vm.testObj, 101, 100); + assert.equal(vm.testObj.error(), $msg.text(), 'Max rule was correctly triggered'); }); -test("Issue #44 - Validation Element - Is Valid Test", function () { +QUnit.test('Issue #44 - Validation Element - Is Valid Test', function(assert) { var vm = { testObj: ko.observable().extend({ min: 1, max: 100 }) }; @@ -612,16 +539,16 @@ test("Issue #44 - Validation Element - Is Valid Test", function () { applyTestBindings(vm); var $el = $('#testElement'); - ok(!$el.hasClass('validationElement'), 'Does not have the validation class'); + assert.ok(!$el.hasClass('validationElement'), 'Does not have the validation class'); vm.testObj(2); // should validate the min rule - ok(vm.testObj.isValid(), "Object is valid"); - ok(!$el.hasClass('validationElement'), 'Correctly does not have the validation class'); + assert.ok(vm.testObj.isValid(), 'Object is valid'); + assert.ok(!$el.hasClass('validationElement'), 'Correctly does not have the validation class'); }); -test("Issue #44 - Validation Element - Is Invalid Test", function () { +QUnit.test('Issue #44 - Validation Element - Is Invalid Test', function(assert) { var vm = { testObj: ko.observable().extend({ min: 1, max: 100 }) }; @@ -635,16 +562,16 @@ test("Issue #44 - Validation Element - Is Invalid Test", function () { applyTestBindings(vm); var $el = $('#testElement'); - ok(!$el.hasClass('validationElement'), 'Does not have the validation class'); + assert.ok(!$el.hasClass('validationElement'), 'Does not have the validation class'); vm.testObj(-1); // should invalidate the min rule - ok(!vm.testObj.isValid(), "Object is not valid"); - ok($el.hasClass('validationElement'), 'Correctly does have the validation class'); + assert.ok(!vm.testObj.isValid(), 'Object is not valid'); + assert.ok($el.hasClass('validationElement'), 'Correctly does have the validation class'); }); -test("Issue #80 - Write HTML5 Validation Attributes programmatically", function () { +QUnit.test('Issue #80 - Write HTML5 Validation Attributes programmatically', function(assert) { var vm = { testObj: ko.observable(15).extend({ min: 1, max: 100, required: true, step: 2, pattern: /blah/i }) @@ -664,19 +591,19 @@ test("Issue #80 - Write HTML5 Validation Attributes programmatically", function var $el = $('#testElement'); var tests = {}; - ko.utils.arrayForEach(['required', 'min', 'max', 'step', 'pattern'], function (attr) { + ko.utils.arrayForEach(['required', 'min', 'max', 'step', 'pattern'], function(attr) { tests[attr] = $el.attr(attr); }); - ok(tests.required, "Required Found"); - strictEqual(tests.min, "1", "Min Found"); - strictEqual(tests.max, "100", "Max Found"); - strictEqual(tests.step, "2", "Step Found"); - strictEqual(tests.pattern, "blah", "Pattern Found"); + assert.ok(tests.required, 'Required Found'); + assert.strictEqual(tests.min, '1', 'Min Found'); + assert.strictEqual(tests.max, '100', 'Max Found'); + assert.strictEqual(tests.step, '2', 'Step Found'); + assert.strictEqual(tests.pattern, 'blah', 'Pattern Found'); }); -test("Issue #400 - Write HTML5 Validation Attributes fails when anonymous rules are used", function () { +QUnit.test('Issue #400 - Write HTML5 Validation Attributes fails when anonymous rules are used', function(assert) { var vm = { testObj: ko.observable(15).extend({required: true}).extend({ @@ -706,19 +633,18 @@ test("Issue #400 - Write HTML5 Validation Attributes fails when anonymous rules var $el = $('#testElement'); var tests = {}; - ko.utils.arrayForEach(['required', 'min', 'max', 'step', 'pattern'], function (attr) { + ko.utils.arrayForEach(['required', 'min', 'max', 'step', 'pattern'], function(attr) { tests[attr] = $el.attr(attr); }); - ok(tests.required, "Required Found"); - ok(!vm.testObj.isValid(), 'observable is NOT valid'); - strictEqual(vm.testObj.error(), "Value must be equal to 1", 'Message is correct'); + assert.ok(tests.required, 'Required Found'); + assert.observableIsNotValid(vm.testObj, 15, 'Value must be equal to 1'); }); -test("Issue #80 - HTML5 attributes - pattern", function () { +QUnit.test('Issue #80 - HTML5 attributes - pattern', function(assert) { var pattern = /something/i; - var patternString = "something"; + var patternString = 'something'; var vm = { testObj: ko.observable('something').extend({ @@ -745,24 +671,25 @@ test("Issue #80 - HTML5 attributes - pattern", function () { // fire the validity check event el.checkValidity(); - strictEqual(param, patternString, "Patterns Match"); - ok(vm.testObj.isValid(), 'Observable is valid'); - ok(el.validity.valid, "Element is showing it is valid"); - strictEqual(vm.testObj(), 'something', 'Observable still works'); + assert.strictEqual(param, patternString, 'Patterns Match'); + assert.ok(vm.testObj.isValid(), 'Observable is valid'); + assert.ok(el.validity.valid, 'Element is showing it is valid'); + assert.strictEqual(vm.testObj(), 'something', 'Observable still works'); }); -module('HTML5 UI Tests', { - setup: function () { - }, - teardown: function () { - ko.cleanNode($('#testContainer')[0]); - $('#testContainer').empty(); +QUnit.module('HTML5 UI Tests', { + afterEach: function() { + var $element = $('#testContainer'); + ko.cleanNode($element[0]); + $element.empty(); ko.validation.reset(); } }); -test("HTML5 Input types", function () { +QUnit.test('HTML5 Input types', function(assert) { + var done = assert.async(); + assert.expect(3); var vm = { invalidEmail: ko.validatedObservable('invalidEmail'), @@ -776,12 +703,9 @@ test("HTML5 Input types", function () { ''); // make sure we parse element attributes - ko.validation.init({ - parseInputAttributes: true - }, true); + ko.validation.init({parseInputAttributes: true}, true); applyTestBindings(vm); - stop(); // The validators for the HTML5 Input types are applied asynchronously, // so we need to wait until the validators have been applied. This is @@ -791,579 +715,545 @@ test("HTML5 Input types", function () { var intervalId = setInterval(function() { if (intervalsWaited++ > 1000) { clearInterval(intervalId); - ok(false, 'Async HTML5 Input validators did not apply within a reasonable amount of time'); - start(); + assert.ok(false, 'Async HTML5 Input validators did not apply within a reasonable amount of time'); } var validatorsReady = vm.invalidEmail.rules().length > 0 && vm.invalidDate.rules().length > 0 && vm.invalidNumber.rules().length > 0; + if (validatorsReady) { - runAssertions(); + clearInterval(intervalId); + assert.ok(!vm.invalidEmail.isValid(), 'Expected email to be considered as invalid.'); + assert.ok(!vm.invalidDate.isValid(), 'Expected date to be considered as invalid.'); + assert.ok(!vm.invalidNumber.isValid(), 'Expected date to be considered as invalid.'); + + done(); } }, 1); - - function runAssertions() - { - clearInterval(intervalId); - - var $emailInput = $('#emailInput'); - var emailInput = $emailInput.get(0); - var $dateInput = $('#dateInput'); - var dateInput = $dateInput.get(0); - var $numberInput = $('#numberInput'); - var numberInput = $numberInput.get(0); - - ok(!vm.invalidEmail.isValid(), 'Expected email to be considered as invalid.'); - ok(!vm.invalidDate.isValid(), 'Expected date to be considered as invalid.'); - ok(!vm.invalidNumber.isValid(), 'Expected date to be considered as invalid.'); - - start(); - } }); -test('min Attribute of 20 should fail for value of 8', function () { +QUnit.test('min Attribute of 20 should fail for value of 8', function(assert) { + var done = assert.async(); + assert.expect(3); var vm = { someNumber: ko.validatedObservable() }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({ - parseInputAttributes: true - }, true); + ko.validation.init({parseInputAttributes: true}, true); applyTestBindings(vm); - stop(); setTimeout(function() { vm.someNumber(8); // should fail the max rule var el = $('#myTestInput'); - ok(el, 'found element'); - ok(!vm.someNumber.isValid(), "Object is not valid"); - equal(vm.someNumber.error(), "Please enter a value greater than or equal to 20.", + assert.ok(el, 'found element'); + assert.ok(!vm.someNumber.isValid(), 'Object is not valid'); + assert.equal(vm.someNumber.error(), 'Please enter a value greater than or equal to 20.', 'Message needs to be formatted correctly'); - start(); + done(); }, 1); }); -test('min Attribute of 20 should fail for value of "8"', function () { +QUnit.test('min Attribute of 20 should fail for value of "8"', function(assert) { + var done = assert.async(); + assert.expect(3); var vm = { someNumber: ko.validatedObservable() }; - addTestHtml(''); - ko.validation.init({ - parseInputAttributes: true - }, true); + addTestHtml(''); + ko.validation.init({parseInputAttributes: true}, true); applyTestBindings(vm); - stop(); setTimeout(function() { - vm.someNumber("8"); // should fail the min rule + vm.someNumber('8'); // should fail the min rule var el = $('#myTestInput'); - ok(el, 'found element'); - ok(!vm.someNumber.isValid(), "Object is not valid"); - equal(vm.someNumber.error(), "Please enter a value greater than or equal to 20.", + assert.ok(el, 'found element'); + assert.ok(!vm.someNumber.isValid(), "Object is not valid"); + assert.equal(vm.someNumber.error(), "Please enter a value greater than or equal to 20.", 'Message needs to be formatted correctly'); - start(); + done(); }, 1); }); -test('min Attribute of 20 should fail for value of "8" with text type', function () { +QUnit.test('min Attribute of 20 should fail for value of "8" with text type', function(assert) { + var done = assert.async(); + assert.expect(3); var vm = { someNumber: ko.validatedObservable() }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({ - parseInputAttributes: true - }, true); + ko.validation.init({parseInputAttributes: true}, true); applyTestBindings(vm); - stop(); setTimeout(function() { - vm.someNumber("8"); // should fail the min rule + vm.someNumber('8'); // should fail the min rule var el = $('#myTestInput'); - ok(el, 'found element'); - ok(!vm.someNumber.isValid(), "Object is not valid"); - equal(vm.someNumber.error(), "Please enter a value greater than or equal to 20.", + assert.ok(el, 'found element'); + assert.ok(!vm.someNumber.isValid(), 'Object is not valid'); + assert.equal(vm.someNumber.error(), 'Please enter a value greater than or equal to 20.', 'Message needs to be formatted correctly'); - start(); + done(); }, 1); }); -test('min Attribute of 20 should pass for value of 110', function () { +QUnit.test('min Attribute of 20 should pass for value of 110', function(assert) { + var done = assert.async(); + assert.expect(2); var vm = { someNumber: ko.validatedObservable() }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({ - parseInputAttributes: true - }, true); + ko.validation.init({parseInputAttributes: true}, true); applyTestBindings(vm); - stop(); setTimeout(function() { vm.someNumber(110); // should validate the min rule var el = $('#myTestInput'); - ok(el, 'found element'); - ok(vm.someNumber.isValid(), "Object is valid"); + assert.ok(el, 'found element'); + assert.ok(vm.someNumber.isValid(), 'Object is valid'); - start(); + done(); }, 1); - }); -test('MIN Attribute of 20 should pass for value of "110"', function () { +QUnit.test('min Attribute of 20 should pass for value of "110"', function(assert) { + var done = assert.async(); + assert.expect(2); var vm = { someNumber: ko.validatedObservable() }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({ - parseInputAttributes: true - }, true); + ko.validation.init({parseInputAttributes: true}, true); applyTestBindings(vm); - stop(); setTimeout(function() { - vm.someNumber("110"); // should validate the min rule + vm.someNumber('110'); // should validate the min rule var el = $('#myTestInput'); - ok(el, 'found element'); - ok(vm.someNumber.isValid(), "Object is valid"); + assert.ok(el, 'found element'); + assert.ok(vm.someNumber.isValid(), 'Object is valid'); - start(); + done(); }, 1); - }); -test('max Attribute of 30 should fail for value of 100', function () { +QUnit.test('max Attribute of 30 should fail for value of 100', function(assert) { + var done = assert.async(); + assert.expect(3); var vm = { someNumber: ko.validatedObservable() }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({ - parseInputAttributes: true - }, true); + ko.validation.init({parseInputAttributes: true}, true); applyTestBindings(vm); - stop(); setTimeout(function() { vm.someNumber(100); // should fail the max rule var el = $('#myTestInput'); - ok(el, 'found element'); - ok(!vm.someNumber.isValid(), "Object is not valid"); - equal(vm.someNumber.error(), "Please enter a value less than or equal to 30.", + assert.ok(el, 'found element'); + assert.ok(!vm.someNumber.isValid(), 'Object is not valid'); + assert.equal(vm.someNumber.error(), 'Please enter a value less than or equal to 30.', 'Message needs to be formatted correctly'); - start(); + done(); }, 1); }); -test('max Attribute of 30 should fail for value of "100"', function () { +QUnit.test('max Attribute of 30 should fail for value of "100"', function(assert) { + var done = assert.async(); + assert.expect(3); var vm = { someNumber: ko.validatedObservable() }; - addTestHtml(''); + addTestHtml(''); ko.validation.init({ parseInputAttributes: true }, true); applyTestBindings(vm); - stop(); setTimeout(function() { - vm.someNumber("100"); // should fail the min rule + vm.someNumber('100'); // should fail the min rule var el = $('#myTestInput'); - ok(el, 'found element'); - ok(!vm.someNumber.isValid(), "Object is not valid"); - equal(vm.someNumber.error(), "Please enter a value less than or equal to 30.", + assert.ok(el, 'found element'); + assert.ok(!vm.someNumber.isValid(), 'Object is not valid'); + assert.equal(vm.someNumber.error(), 'Please enter a value less than or equal to 30.', 'Message needs to be formatted correctly'); - start(); + done(); }, 1); }); -test('max Attribute of 30 should fail for value of "100" with text type', function () { +QUnit.test('max Attribute of 30 should fail for value of "100" with text type', function(assert) { + var done = assert.async(); + assert.expect(3); var vm = { someNumber: ko.validatedObservable() }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({ - parseInputAttributes: true - }, true); + ko.validation.init({parseInputAttributes: true}, true); applyTestBindings(vm); - stop(); setTimeout(function() { vm.someNumber(100); // should fail the min rule var el = $('#myTestInput'); - ok(el, 'found element'); - ok(!vm.someNumber.isValid(), "Object is not valid"); - equal(vm.someNumber.error(), "Please enter a value less than or equal to 30.", + assert.ok(el, 'found element'); + assert.ok(!vm.someNumber.isValid(), 'Object is not valid'); + assert.equal(vm.someNumber.error(), 'Please enter a value less than or equal to 30.', 'Message needs to be formatted correctly'); - start(); + done(); }, 1); }); -test('max Attribute of 30 should pass for value of 5', function () { +QUnit.test('max Attribute of 30 should pass for value of 5', function(assert) { + var done = assert.async(); + assert.expect(2); var vm = { someNumber: ko.validatedObservable() }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({ - parseInputAttributes: true - }, true); + ko.validation.init({parseInputAttributes: true}, true); applyTestBindings(vm); - stop(); setTimeout(function() { vm.someNumber(5); // should validate the min rule var el = $('#myTestInput'); - ok(el, 'found element'); - ok(vm.someNumber.isValid(), "Object is valid"); + assert.ok(el, 'found element'); + assert.ok(vm.someNumber.isValid(), 'Object is valid'); - start(); + done(); }, 1); - }); -test('max Attribute of 30 should pass for value of "5"', function () { +QUnit.test('max Attribute of 30 should pass for value of "5"', function(assert) { + var done = assert.async(); + assert.expect(2); var vm = { someNumber: ko.validatedObservable() }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({ - parseInputAttributes: true - }, true); + ko.validation.init({parseInputAttributes: true}, true); applyTestBindings(vm); - stop(); setTimeout(function() { - vm.someNumber("5"); // should validate the min rule + vm.someNumber('5'); // should validate the min rule var el = $('#myTestInput'); - ok(el, 'found element'); - ok(vm.someNumber.isValid(), "Object is valid"); + assert.ok(el, 'found element'); + assert.ok(vm.someNumber.isValid(), 'Object is valid'); - start(); + done(); }, 1); - }); -test('max Attribute of 2010-09 should fail for value of 2011-03', function () { +QUnit.test('max Attribute of 2010-09 should fail for value of 2011-03', function(assert) { + var done = assert.async(); + assert.expect(2); var vm = { someNumber: ko.validatedObservable() }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({ - parseInputAttributes: true - }, true); + ko.validation.init({parseInputAttributes: true}, true); applyTestBindings(vm); - stop(); setTimeout(function() { - vm.someNumber("2011-03"); // should fail the max rule + vm.someNumber('2011-03'); // should fail the max rule var el = $('#myTestInput'); - ok(el, 'found element'); - ok(!vm.someNumber.isValid(), "Object is not valid"); + assert.ok(el, 'found element'); + assert.ok(!vm.someNumber.isValid(), 'Object is not valid'); - start(); + done(); }, 1); }); -test('max Attribute of 2010-09 should succeed for value of 2010-08', function () { +QUnit.test('max Attribute of 2010-09 should succeed for value of 2010-08', function(assert) { + var done = assert.async(); + assert.expect(2); var vm = { someNumber: ko.validatedObservable() }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({ - parseInputAttributes: true - }, true); + ko.validation.init({parseInputAttributes: true}, true); applyTestBindings(vm); - stop(); setTimeout(function() { - vm.someNumber("2010-08"); // should succeed the max rule + vm.someNumber('2010-08'); // should succeed the max rule var el = $('#myTestInput'); - ok(el, 'found element'); - ok(vm.someNumber.isValid(), "Object is valid"); + assert.ok(el, 'found element'); + assert.ok(vm.someNumber.isValid(), 'Object is valid'); - start(); + done(); }, 1); }); -test('min Attribute of 2010-09 should fail for value of 2010-08', function () { +QUnit.test('min Attribute of 2010-09 should fail for value of 2010-08', function(assert) { + var done = assert.async(); + assert.expect(3); var vm = { someNumber: ko.validatedObservable() }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({ - parseInputAttributes: true - }, true); + ko.validation.init({parseInputAttributes: true}, true); applyTestBindings(vm); - stop(); setTimeout(function() { - vm.someNumber("2010-08"); // should fail the min rule + vm.someNumber('2010-08'); // should fail the min rule var el = $('#myTestInput'); - ok(el, 'found element'); - ok(!vm.someNumber.isValid(), "Object is valid"); - equal(vm.someNumber.error(), "Please enter a value greater than or equal to 2010-09.", + assert.ok(el, 'found element'); + assert.ok(!vm.someNumber.isValid(), 'Object is valid'); + assert.equal(vm.someNumber.error(), 'Please enter a value greater than or equal to 2010-09.', 'Message needs to be formatted correctly'); - start(); + done(); }, 1); }); -test('min Attribute of 2012-05 should fail for value of 2011-01', function () { +QUnit.test('min Attribute of 2012-05 should fail for value of 2011-01', function(assert) { + var done = assert.async(); + assert.expect(3); var vm = { someNumber: ko.validatedObservable() }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({ - parseInputAttributes: true - }, true); + ko.validation.init({parseInputAttributes: true}, true); applyTestBindings(vm); - stop(); setTimeout(function() { - vm.someNumber("2011-01"); // should fail the min rule + vm.someNumber('2011-01'); // should fail the min rule var el = $('#myTestInput'); - ok(el, 'found element'); - ok(!vm.someNumber.isValid(), "Object is valid"); - equal(vm.someNumber.error(), "Please enter a value greater than or equal to 2012-05.", + assert.ok(el, 'found element'); + assert.ok(!vm.someNumber.isValid(), 'Object is valid'); + assert.equal(vm.someNumber.error(), 'Please enter a value greater than or equal to 2012-05.', 'Message needs to be formatted correctly'); - start(); + done(); }, 1); }); -test('min Attribute of 2012-03 should succeed for value of 2013-01', function () { +QUnit.test('min Attribute of 2012-03 should succeed for value of 2013-01', function(assert) { + var done = assert.async(); + assert.expect(2); var vm = { someNumber: ko.validatedObservable() }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({ - parseInputAttributes: true - }, true); + ko.validation.init({parseInputAttributes: true}, true); applyTestBindings(vm); - stop(); setTimeout(function() { - vm.someNumber("2013-01"); // should succeed the min rule + vm.someNumber('2013-01'); // should succeed the min rule var el = $('#myTestInput'); - ok(el, 'found element'); - ok(vm.someNumber.isValid(), "Object is valid"); + assert.ok(el, 'found element'); + assert.ok(vm.someNumber.isValid(), 'Object is valid'); - start(); + done(); }, 1); }); -test('max Attribute of 2010-W09 should fail for value of 2011-W03', function () { +QUnit.test('max Attribute of 2010-W09 should fail for value of 2011-W03', function(assert) { + var done = assert.async(); + assert.expect(3); var vm = { someNumber: ko.validatedObservable() }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({ - parseInputAttributes: true - }, true); + ko.validation.init({parseInputAttributes: true}, true); applyTestBindings(vm); - stop(); setTimeout(function() { - vm.someNumber("2011-W03"); // should fail the max rule + vm.someNumber('2011-W03'); // should fail the max rule var el = $('#myTestInput'); - ok(el, 'found element'); - ok(!vm.someNumber.isValid(), "Object is not valid"); - equal(vm.someNumber.error(), "Please enter a value less than or equal to 2010-W09.", + assert.ok(el, 'found element'); + assert.ok(!vm.someNumber.isValid(), 'Object is not valid'); + assert.equal(vm.someNumber.error(), 'Please enter a value less than or equal to 2010-W09.', 'Message needs to be formatted correctly'); - start(); + done(); }, 1); }); -test('max Attribute of 2010-W09 should succeed for value of 2010-W08', function () { +QUnit.test('max Attribute of 2010-W09 should succeed for value of 2010-W08', function(assert) { + var done = assert.async(); + assert.expect(2); var vm = { someNumber: ko.validatedObservable() }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({ - parseInputAttributes: true - }, true); + ko.validation.init({parseInputAttributes: true}, true); applyTestBindings(vm); - stop(); setTimeout(function() { - vm.someNumber("2010-W08"); // should succeed the max rule + vm.someNumber('2010-W08'); // should succeed the max rule var el = $('#myTestInput'); - ok(el, 'found element'); - ok(vm.someNumber.isValid(), "Object is valid"); + assert.ok(el, 'found element'); + assert.ok(vm.someNumber.isValid(), 'Object is valid'); - start(); + done(); }, 1); }); -test('min Attribute of 2010-W09 should fail for value of 2010-W08', function () { +QUnit.test('min Attribute of 2010-W09 should fail for value of 2010-W08', function(assert) { + var done = assert.async(); + assert.expect(3); var vm = { someNumber: ko.validatedObservable() }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({ - parseInputAttributes: true - }, true); + ko.validation.init({parseInputAttributes: true}, true); applyTestBindings(vm); - stop(); setTimeout(function() { - vm.someNumber("2010-W08"); // should fail the min rule + vm.someNumber('2010-W08'); // should fail the min rule var el = $('#myTestInput'); - ok(el, 'found element'); - ok(!vm.someNumber.isValid(), "Object is valid"); - equal(vm.someNumber.error(), "Please enter a value greater than or equal to 2010-W09.", + assert.ok(el, 'found element'); + assert.ok(!vm.someNumber.isValid(), 'Object is valid'); + assert.equal(vm.someNumber.error(), 'Please enter a value greater than or equal to 2010-W09.', 'Message needs to be formatted correctly'); - start(); + done(); }, 1); }); -test('min Attribute of 2012-W05 should fail for value of 2011-W01', function () { +QUnit.test('min Attribute of 2012-W05 should fail for value of 2011-W01', function(assert) { + var done = assert.async(); + assert.expect(3); var vm = { someNumber: ko.validatedObservable() }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({ - parseInputAttributes: true - }, true); + ko.validation.init({parseInputAttributes: true}, true); applyTestBindings(vm); - stop(); setTimeout(function() { - vm.someNumber("2011-W01"); // should fail the min rule + vm.someNumber('2011-W01'); // should fail the min rule var el = $('#myTestInput'); - ok(el, 'found element'); - ok(!vm.someNumber.isValid(), "Object is valid"); - equal(vm.someNumber.error(), "Please enter a value greater than or equal to 2012-W05.", + assert.ok(el, 'found element'); + assert.ok(!vm.someNumber.isValid(), 'Object is valid'); + assert.equal(vm.someNumber.error(), 'Please enter a value greater than or equal to 2012-W05.', 'Message needs to be formatted correctly'); - start(); + done(); }, 1); }); -test('min Attribute of 2012-W03 should succeed for value of 2013-W01', function () { +QUnit.test('min Attribute of 2012-W03 should succeed for value of 2013-W01', function(assert) { + var done = assert.async(); + assert.expect(2); var vm = { someNumber: ko.validatedObservable() }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({ - parseInputAttributes: true - }, true); + ko.validation.init({parseInputAttributes: true}, true); applyTestBindings(vm); - stop(); setTimeout(function() { - vm.someNumber("2013-W01"); // should succeed the min rule + vm.someNumber('2013-W01'); // should succeed the min rule var el = $('#myTestInput'); - ok(el, 'found element'); - ok(vm.someNumber.isValid(), "Object is valid"); + assert.ok(el, 'found element'); + assert.ok(vm.someNumber.isValid(), 'Object is valid'); - start(); + done(); }, 1); }); //#endregion + From 72ae9aa11aad009e57aaeae7ca41db878dfcfce7 Mon Sep 17 00:00:00 2001 From: crissdev Date: Wed, 17 Dec 2014 23:06:01 +0200 Subject: [PATCH 110/165] Use native String.trim if available Closes #484 --- Dist/knockout.validation.js | 12 ++++++++---- Dist/knockout.validation.min.js | 2 +- Dist/knockout.validation.min.js.map | 2 +- Src/rules.js | 12 ++++++++---- 4 files changed, 18 insertions(+), 10 deletions(-) diff --git a/Dist/knockout.validation.js b/Dist/knockout.validation.js index 12bfd0cd..5045a582 100644 --- a/Dist/knockout.validation.js +++ b/Dist/knockout.validation.js @@ -668,16 +668,20 @@ extend(ko.validation, api); kv.rules = {}; kv.rules['required'] = { validator: function (val, required) { - var stringTrimRegEx = /^\s+|\s+$/g, - testVal; + var testVal; if (val === undefined || val === null) { return !required; } testVal = val; - if (typeof (val) === "string") { - testVal = val.replace(stringTrimRegEx, ''); + if (typeof (val) === 'string') { + if (String.prototype.trim) { + testVal = val.trim(); + } + else { + testVal = val.replace(/^\s+|\s+$/g, ''); + } } if (!required) {// if they passed: { required: false }, then don't require this diff --git a/Dist/knockout.validation.min.js b/Dist/knockout.validation.min.js index 0e125634..57f09663 100644 --- a/Dist/knockout.validation.min.js +++ b/Dist/knockout.validation.min.js @@ -7,5 +7,5 @@ =============================================================================== */ -!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||e instanceof Date||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for week input. Should look like '2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for month input. Should look like '2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:h(c.params))?!0:(a.setError(f.formatMessage(c.message||b.message,h(c.params),a)),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,h(c.params),a)),a.__valid__(e)),void a.isValidating(!1)):void a.isValidating(!1)};b.validator(a(),h(c.params||!0),d)}if("undefined"==typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0,live:!1},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},isNumber:function(a){return!isNaN(a)},isObservableArray:function(a){return!!a&&"function"==typeof a.remove&&"function"==typeof a.removeAll&&"function"==typeof a.destroy&&"function"==typeof a.destroyAll&&"function"==typeof a.indexOf&&"function"==typeof a.replace},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return!!(a&&a.rules&&a.isValid&&a.isModified)},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},forEach:function(a,b){if(f.utils.isArray(a))return i(a,b);for(var c in a)a.hasOwnProperty(c)&&b(a[c],c)}}}();var m=function(){function b(a){i(a.subscriptions,function(a){a.dispose()}),a.subscriptions=[]}function c(a){a.options.deep&&(i(a.flagged,function(a){delete a.__kv_traversed}),a.flagged.length=0),a.options.live||b(a)}function d(a,d){d.validatables=[],b(d),e(a,d),c(d)}function e(b,c,d){var f=[],g=b.peek?b.peek():b;b.__kv_traversed!==!0&&(c.options.deep&&(b.__kv_traversed=!0,c.flagged.push(b)),d=void 0!==d?d:c.options.deep?1:-1,a.isObservable(b)&&(b.isValid||b.extend({validatable:!0}),c.validatables.push(b),c.options.live&&n.isObservableArray(b)&&c.subscriptions.push(b.subscribe(function(){c.graphMonitor.valueHasMutated()}))),g&&!g._destroy&&(n.isArray(g)?f=g:n.isObject(g)&&(f=n.values(g))),0!==d&&n.forEach(f,function(a){a&&!a.nodeType&&e(a,c,d+1)}))}function k(a){var b=[];return i(a,function(a){a.isValid()||b.push(a.error())}),b}var l=0,m=f.configuration,n=f.utils;return{init:function(a,b){l>0&&!b||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||m.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||m.errorMessageClass,j(m,a),m.registerExtenders&&f.registerExtenders(),l=1)},configure:function(a){f.init(a)},reset:f.configuration.reset,group:function(b,c){c=j(j({},m.grouping),c);var e={options:c,graphMonitor:a.observable(),flagged:[],subscriptions:[],validatables:[]},f=null;return c.observable?(d(b,e),f=a.computed(function(){return e.graphMonitor(),d(b,e),k(e.validatables)})):f=function(){return d(b,e),k(e.validatables)},f.showAllMessages=function(a){void 0===a&&(a=!0),f(),i(e.validatables,function(b){b.isModified(a)})},f.isAnyMessageShown=function(){var a=!1;return f(),a=!!g.arrayFirst(e.validatables,function(a){return!a.isValid()&&a.isModified()})},f},formatMessage:function(a,b,c){if(n.isObject(b)&&b.typeAttr&&(b=b.value),"function"==typeof a)return a(b,c);var d=h(b)||[];return n.isArray(d)||(d=[d]),a.replace(/{(\d+)}/gi,function(a,b){return"undefined"!=typeof d[b]?d[b]:a})},addRule:function(a,b){return a.extend({validatable:!0}),a.rules.push(b),a},addAnonymousRule:function(a,b){void 0===b.message&&(b.message="Error"),b.onlyIf&&(b.condition=b.onlyIf),f.addRule(a,b)},addExtender:function(b){a.extenders[b]=function(a,c){return c&&(c.message||c.onlyIf)?f.addRule(a,{rule:b,message:c.message,params:n.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(m.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=n.getConfigOptions(a).errorMessageClass,n.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(n.hasAttribute(a,c)){var d=a.getAttribute(c)||!0;if("min"===c||"max"===c){var e=a.getAttribute("type");"undefined"!=typeof e&&e||(e="text"),d={typeAttr:e,value:d}}f.addRule(b(),{rule:c,params:d})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(a,b){var c=b();if(c&&c.rules){var d=c.rules();i(f.configuration.html5Attributes,function(b){var c,e=g.arrayFirst(d,function(a){return a.rule&&a.rule.toLowerCase()===b.toLowerCase()});e&&(c=e.params,"pattern"===e.rule&&e.params instanceof RegExp&&(c=e.params.source),a.setAttribute(b,c))}),d=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var d=function(b,c){if(b&&c)for(var e in c)if(c.hasOwnProperty(e)){var g=c[e];if(b[e]){var i=b[e],j=h(i),k={},l={};for(var m in g)g.hasOwnProperty(m)&&(f.rules[m]?k[m]=g[m]:l[m]=g[m]);if(a.isObservable(i)&&i.extend(k),j&&n.isArray(j))for(var o=0;o0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}."},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address."},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date."},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[-/](?:0?[1-9]|1[012])[-/](?:0?[1-9]|[12][0-9]|3[01])$/.test(a):!0},message:"Please enter a proper date."},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number."},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit."},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number."},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal."},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(c,function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateInputElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.textInput&&f.makeBindingHandlerValidatable("textInput"),f.makeBindingHandlerValidatable("selectedOptions"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),i=(h(d),!1),j=!1;if(null===d||"undefined"==typeof d)throw new Error("Cannot bind validationMessage to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");i=d.isModified(),j=d.isValid();var k=null;(!e.messagesOnModified||i)&&(k=j?null:d.error);var l=!e.messagesOnModified||i?!j:!1,m="none"!==b.style.display;e.allowHtmlMessages?g.setHtml(b,k):a.bindingHandlers.text.update(b,function(){return k}),m&&!l?b.style.display="none":!m&&l&&(b.style.display="")}},a.bindingHandlers.validationElement={update:function(b,c,d){var e=c(),g=f.utils.getConfigOptions(b),i=(h(e),!1),j=!1;if(null===e||"undefined"==typeof e)throw new Error("Cannot bind validationElement to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!e.isValid||!e.isModified)throw new Error("Observable is not validatable");i=e.isModified(),j=e.isValid();var k=function(){var a={},b=!g.decorateElementOnModified||i?!j:!1;return a[g.errorElementClass]=b,a};a.bindingHandlers.css.update(b,k,d),g.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!g.errorsAsTitleOnModified||i,c=f.utils.getOriginalElementTitle(b);return a&&!j?{title:e.error,"data-orig-title":c}:!a||j?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){b.error(a),b.__valid__(!1)},b.clearError=function(){return b.error(null),b.__valid__(!0),b};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){b(),b.rules();return f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified.getSubscriptionsCount()>0&&(b.isModified._subscriptions.change=[]),b.isValidating.getSubscriptionsCount()>0&&(b.isValidating._subscriptions.change=[]),b.__valid__.getSubscriptionsCount()>0&&(b.__valid__._subscriptions.change=[]),g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=c.rule?f.rules[c.rule]:c,b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0},f.localize=function(a){var b;for(b in a)f.rules.hasOwnProperty(b)&&(f.rules[b].message=a[b])},a.applyBindingsWithValidation=function(b,c,d){var e,g=document.body;c&&c.nodeType?(g=c,e=d):e=c,f.init(),e&&(e=j(j({},f.configuration),e),f.utils.setDomData(g,e)),a.applyBindings(b,c)};var n=a.applyBindings;a.applyBindings=function(a,b){f.init(),n(a,b)},a.validatedObservable=function(b,c){if(!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var d=a.observable(b);return d.errors=f.group(b,c),d.isValid=a.observable(0===d.errors().length),a.isObservable(d.errors)?d.errors.subscribe(function(a){d.isValid(0===a.length)}):a.computed(d.errors).subscribe(function(a){d.isValid(0===a.length)}),d}}); +!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||e instanceof Date||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for week input. Should look like '2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for month input. Should look like '2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:h(c.params))?!0:(a.setError(f.formatMessage(c.message||b.message,h(c.params),a)),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,h(c.params),a)),a.__valid__(e)),void a.isValidating(!1)):void a.isValidating(!1)};b.validator(a(),h(c.params||!0),d)}if("undefined"==typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0,live:!1},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},isNumber:function(a){return!isNaN(a)},isObservableArray:function(a){return!!a&&"function"==typeof a.remove&&"function"==typeof a.removeAll&&"function"==typeof a.destroy&&"function"==typeof a.destroyAll&&"function"==typeof a.indexOf&&"function"==typeof a.replace},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return!!(a&&a.rules&&a.isValid&&a.isModified)},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},forEach:function(a,b){if(f.utils.isArray(a))return i(a,b);for(var c in a)a.hasOwnProperty(c)&&b(a[c],c)}}}();var m=function(){function b(a){i(a.subscriptions,function(a){a.dispose()}),a.subscriptions=[]}function c(a){a.options.deep&&(i(a.flagged,function(a){delete a.__kv_traversed}),a.flagged.length=0),a.options.live||b(a)}function d(a,d){d.validatables=[],b(d),e(a,d),c(d)}function e(b,c,d){var f=[],g=b.peek?b.peek():b;b.__kv_traversed!==!0&&(c.options.deep&&(b.__kv_traversed=!0,c.flagged.push(b)),d=void 0!==d?d:c.options.deep?1:-1,a.isObservable(b)&&(b.isValid||b.extend({validatable:!0}),c.validatables.push(b),c.options.live&&n.isObservableArray(b)&&c.subscriptions.push(b.subscribe(function(){c.graphMonitor.valueHasMutated()}))),g&&!g._destroy&&(n.isArray(g)?f=g:n.isObject(g)&&(f=n.values(g))),0!==d&&n.forEach(f,function(a){a&&!a.nodeType&&e(a,c,d+1)}))}function k(a){var b=[];return i(a,function(a){a.isValid()||b.push(a.error())}),b}var l=0,m=f.configuration,n=f.utils;return{init:function(a,b){l>0&&!b||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||m.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||m.errorMessageClass,j(m,a),m.registerExtenders&&f.registerExtenders(),l=1)},configure:function(a){f.init(a)},reset:f.configuration.reset,group:function(b,c){c=j(j({},m.grouping),c);var e={options:c,graphMonitor:a.observable(),flagged:[],subscriptions:[],validatables:[]},f=null;return c.observable?(d(b,e),f=a.computed(function(){return e.graphMonitor(),d(b,e),k(e.validatables)})):f=function(){return d(b,e),k(e.validatables)},f.showAllMessages=function(a){void 0===a&&(a=!0),f(),i(e.validatables,function(b){b.isModified(a)})},f.isAnyMessageShown=function(){var a=!1;return f(),a=!!g.arrayFirst(e.validatables,function(a){return!a.isValid()&&a.isModified()})},f},formatMessage:function(a,b,c){if(n.isObject(b)&&b.typeAttr&&(b=b.value),"function"==typeof a)return a(b,c);var d=h(b)||[];return n.isArray(d)||(d=[d]),a.replace(/{(\d+)}/gi,function(a,b){return"undefined"!=typeof d[b]?d[b]:a})},addRule:function(a,b){return a.extend({validatable:!0}),a.rules.push(b),a},addAnonymousRule:function(a,b){void 0===b.message&&(b.message="Error"),b.onlyIf&&(b.condition=b.onlyIf),f.addRule(a,b)},addExtender:function(b){a.extenders[b]=function(a,c){return c&&(c.message||c.onlyIf)?f.addRule(a,{rule:b,message:c.message,params:n.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(m.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=n.getConfigOptions(a).errorMessageClass,n.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(n.hasAttribute(a,c)){var d=a.getAttribute(c)||!0;if("min"===c||"max"===c){var e=a.getAttribute("type");"undefined"!=typeof e&&e||(e="text"),d={typeAttr:e,value:d}}f.addRule(b(),{rule:c,params:d})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(a,b){var c=b();if(c&&c.rules){var d=c.rules();i(f.configuration.html5Attributes,function(b){var c,e=g.arrayFirst(d,function(a){return a.rule&&a.rule.toLowerCase()===b.toLowerCase()});e&&(c=e.params,"pattern"===e.rule&&e.params instanceof RegExp&&(c=e.params.source),a.setAttribute(b,c))}),d=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var d=function(b,c){if(b&&c)for(var e in c)if(c.hasOwnProperty(e)){var g=c[e];if(b[e]){var i=b[e],j=h(i),k={},l={};for(var m in g)g.hasOwnProperty(m)&&(f.rules[m]?k[m]=g[m]:l[m]=g[m]);if(a.isObservable(i)&&i.extend(k),j&&n.isArray(j))for(var o=0;o0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}."},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address."},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date."},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[-/](?:0?[1-9]|1[012])[-/](?:0?[1-9]|[12][0-9]|3[01])$/.test(a):!0},message:"Please enter a proper date."},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number."},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit."},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number."},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal."},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(c,function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateInputElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.textInput&&f.makeBindingHandlerValidatable("textInput"),f.makeBindingHandlerValidatable("selectedOptions"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),i=(h(d),!1),j=!1;if(null===d||"undefined"==typeof d)throw new Error("Cannot bind validationMessage to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");i=d.isModified(),j=d.isValid();var k=null;(!e.messagesOnModified||i)&&(k=j?null:d.error);var l=!e.messagesOnModified||i?!j:!1,m="none"!==b.style.display;e.allowHtmlMessages?g.setHtml(b,k):a.bindingHandlers.text.update(b,function(){return k}),m&&!l?b.style.display="none":!m&&l&&(b.style.display="")}},a.bindingHandlers.validationElement={update:function(b,c,d){var e=c(),g=f.utils.getConfigOptions(b),i=(h(e),!1),j=!1;if(null===e||"undefined"==typeof e)throw new Error("Cannot bind validationElement to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!e.isValid||!e.isModified)throw new Error("Observable is not validatable");i=e.isModified(),j=e.isValid();var k=function(){var a={},b=!g.decorateElementOnModified||i?!j:!1;return a[g.errorElementClass]=b,a};a.bindingHandlers.css.update(b,k,d),g.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!g.errorsAsTitleOnModified||i,c=f.utils.getOriginalElementTitle(b);return a&&!j?{title:e.error,"data-orig-title":c}:!a||j?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){b.error(a),b.__valid__(!1)},b.clearError=function(){return b.error(null),b.__valid__(!0),b};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){b(),b.rules();return f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified.getSubscriptionsCount()>0&&(b.isModified._subscriptions.change=[]),b.isValidating.getSubscriptionsCount()>0&&(b.isValidating._subscriptions.change=[]),b.__valid__.getSubscriptionsCount()>0&&(b.__valid__._subscriptions.change=[]),g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=c.rule?f.rules[c.rule]:c,b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0},f.localize=function(a){var b;for(b in a)f.rules.hasOwnProperty(b)&&(f.rules[b].message=a[b])},a.applyBindingsWithValidation=function(b,c,d){var e,g=document.body;c&&c.nodeType?(g=c,e=d):e=c,f.init(),e&&(e=j(j({},f.configuration),e),f.utils.setDomData(g,e)),a.applyBindings(b,c)};var n=a.applyBindings;a.applyBindings=function(a,b){f.init(),n(a,b)},a.validatedObservable=function(b,c){if(!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var d=a.observable(b);return d.errors=f.group(b,c),d.isValid=a.observable(0===d.errors().length),a.isObservable(d.errors)?d.errors.subscribe(function(a){d.isValid(0===a.length)}):a.computed(d.errors).subscribe(function(a){d.isValid(0===a.length)}),d}}); //# sourceMappingURL=knockout.validation.min.js.map \ No newline at end of file diff --git a/Dist/knockout.validation.min.js.map b/Dist/knockout.validation.min.js.map index c7295a77..080cb3eb 100644 --- a/Dist/knockout.validation.min.js.map +++ b/Dist/knockout.validation.min.js.map @@ -1 +1 @@ -{"version":3,"file":"knockout.validation.min.js","sources":["knockout.validation.js"],"names":["factory","require","exports","module","define","ko","validation","minMaxValidatorFactory","validatorName","isMaxValidation","val","options","kv","utils","isEmptyVal","comparisonValue","type","undefined","typeAttr","value","isNaN","Date","regex","valMatches","comparisonValueMatches","toLowerCase","match","parseFloat","validateSync","observable","rule","ctx","validator","params","unwrap","setError","formatMessage","message","validateAsync","isValidating","callBack","valObj","isValid","msg","__valid__","error","koUtils","unwrapObservable","forEach","arrayForEach","extend","defaults","registerExtenders","messagesOnModified","errorsAsTitle","errorsAsTitleOnModified","messageTemplate","insertMessages","parseInputAttributes","writeInputAttributes","decorateInputElement","decorateElementOnModified","errorClass","errorElementClass","errorMessageClass","allowHtmlMessages","grouping","deep","live","validate","configuration","html5Attributes","html5InputTypes","reset","seedId","getTime","domData","domDataKey","isArray","o","Object","prototype","toString","call","isObject","isNumber","isObservableArray","instance","values","r","i","hasOwnProperty","push","getValue","hasAttribute","node","attr","getAttribute","element","setAttribute","isValidatable","rules","isModified","insertAfter","newNode","parentNode","insertBefore","nextSibling","newId","getConfigOptions","contextFor","setDomData","data","key","getDomData","nodeType","context","getOriginalElementTitle","savedOriginalTitle","currentTitle","title","hasSavedOriginalTitle","async","expr","window","setImmediate","setTimeout","object","callback","prop","api","cleanUpSubscriptions","subscriptions","subscription","dispose","flagged","obj","__kv_traversed","length","runTraversal","validatables","traverseGraph","level","objValues","peek","isObservable","validatable","subscribe","graphMonitor","valueHasMutated","_destroy","collectErrors","array","errors","isInitialized","init","force","configure","group","result","computed","showAllMessages","show","isAnyMessageShown","invalidAndModifiedPresent","arrayFirst","replacements","replace","index","addRule","addAnonymousRule","ruleObj","onlyIf","condition","addExtender","ruleName","extenders","insertValidationMessage","span","document","createElement","className","parseInputValidationAttributes","valueAccessor","currentType","writeInputValidationAttributes","contexts","RegExp","source","makeBindingHandlerValidatable","handlerName","bindingHandlers","allBindingsAccessor","viewModel","bindingContext","setRules","target","definition","ruleDefinitions","targetValue","unwrappedTargetValue","nonRules","required","testVal","stringTrimRegEx","minLength","normalizedVal","maxLength","step","dif","Math","abs","test","phoneNumber","otherValue","c","collection","external","externalValue","counter","arrayFilter","item","config","validationMessageElement","renderTemplate","field","applyBindingsToNode","validationMessage","validationElement","textInput","update","obsv","Error","isVisible","isCurrentlyVisible","style","display","setHtml","text","cssSettingsAccessor","css","shouldShow","hasModification","data-orig-title","newConfig","enable","validationOptions","throttleEvaluation","throttle","observableArray","clearError","h_change","h_obsValidationTrigger","read","validateObservable","_disposeValidation","removeAll","getSubscriptionsCount","_subscriptions","ruleContexts","len","localize","msgTranslations","applyBindingsWithValidation","rootNode","body","applyBindings","origApplyBindings","validatedObservable","initialValue"],"mappings":";;;;;;;;;CAUC,SAAUA,GAGgB,kBAAZC,UAA6C,gBAAZC,UAA0C,gBAAXC,QAEvEH,EAAQC,QAAQ,YAAaC,SACJ,kBAAXE,SAAyBA,OAAY,IAEnDA,QAAQ,WAAY,WAAYJ,GAGhCA,EAAQK,GAAIA,GAAGC,gBAErB,SAAWD,EAAIH,GA4pBjB,QAASK,GAAuBC,GAC5B,GAAIC,GAAoC,QAAlBD,CAEtB,OAAO,UAAUE,EAAKC,GAClB,GAAIC,EAAGC,MAAMC,WAAWJ,GACpB,OAAO,CAGX,IAAIK,GAAiBC,CACIC,UAArBN,EAAQO,UAGRF,EAAO,OACPD,EAAkBJ,IAElBK,EAAOL,EAAQO,SACfH,EAAkBJ,EAAQQ,OAKzBC,MAAML,IAAsBA,YAA2BM,QACxDL,EAAO,SAGX,IAAIM,GAAOC,EAAYC,CACvB,QAAQR,EAAKS,eACT,IAAK,OAGD,GAFAH,EAAQ,qBACRC,EAAab,EAAIgB,MAAMJ,GACJ,OAAfC,EACA,KAAM,qBAAuBf,EAAgB,+HA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GACR1P,EAAGyF,MAAMV,eAAe7D,KAC3BlB,EAAGyF,MAAMvE,GAAMO,QAAUiO,EAAgBxO,KAU5CzB,EAAGkQ,4BAA8B,SAAUtE,EAAWuE,EAAU7P,GAC/D,GACCmN,GADG/H,EAAOoF,SAASsF,IAGhBD,IAAYA,EAASrJ,UACxBpB,EAAOyK,EACP1C,EAASnN,GAGTmN,EAAS0C,EAGV5P,EAAG+I,OAECmE,IACHA,EAAS5K,EAAOA,KAAWtC,EAAG0D,eAAgBwJ,GAC9ClN,EAAGC,MAAMkG,WAAWhB,EAAM+H,IAG3BzN,EAAGqQ,cAAczE,EAAWuE,GAI7B,IAAIG,GAAoBtQ,EAAGqQ,aAC3BrQ,GAAGqQ,cAAgB,SAAUzE,EAAWuE,GAEvC5P,EAAG+I,OAEHgH,EAAkB1E,EAAWuE,IAG9BnQ,EAAGuQ,oBAAsB,SAAUC,EAAclQ,GAChD,IAAKC,EAAGC,MAAMuE,SAASyL,GAAiB,MAAOxQ,GAAGwB,WAAWgP,GAAc3N,QAASgG,aAAa,GAEjG,IAAIqF,GAAOlO,EAAGwB,WAAWgP,EAgBzB,OAfAtC,GAAK9E,OAAS7I,EAAGkJ,MAAM+G,EAAclQ,GACrC4N,EAAK7L,QAAUrC,EAAGwB,WAAoC,IAAzB0M,EAAK9E,SAASf,QAGvCrI,EAAG4I,aAAasF,EAAK9E,QACxB8E,EAAK9E,OAAON,UAAU,SAAUM,GAC9B8E,EAAK7L,QAA0B,IAAlB+G,EAAOf,UAIrBrI,EAAG2J,SAASuE,EAAK9E,QAAQN,UAAU,SAAUM,GAC5C8E,EAAK7L,QAA0B,IAAlB+G,EAAOf,UAIhB6F"} \ No newline at end of file +{"version":3,"file":"knockout.validation.min.js","sources":["knockout.validation.js"],"names":["factory","require","exports","module","define","ko","validation","minMaxValidatorFactory","validatorName","isMaxValidation","val","options","kv","utils","isEmptyVal","comparisonValue","type","undefined","typeAttr","value","isNaN","Date","regex","valMatches","comparisonValueMatches","toLowerCase","match","parseFloat","validateSync","observable","rule","ctx","validator","params","unwrap","setError","formatMessage","message","validateAsync","isValidating","callBack","valObj","isValid","msg","__valid__","error","koUtils","unwrapObservable","forEach","arrayForEach","extend","defaults","registerExtenders","messagesOnModified","errorsAsTitle","errorsAsTitleOnModified","messageTemplate","insertMessages","parseInputAttributes","writeInputAttributes","decorateInputElement","decorateElementOnModified","errorClass","errorElementClass","errorMessageClass","allowHtmlMessages","grouping","deep","live","validate","configuration","html5Attributes","html5InputTypes","reset","seedId","getTime","domData","domDataKey","isArray","o","Object","prototype","toString","call","isObject","isNumber","isObservableArray","instance","values","r","i","hasOwnProperty","push","getValue","hasAttribute","node","attr","getAttribute","element","setAttribute","isValidatable","rules","isModified","insertAfter","newNode","parentNode","insertBefore","nextSibling","newId","getConfigOptions","contextFor","setDomData","data","key","getDomData","nodeType","context","getOriginalElementTitle","savedOriginalTitle","currentTitle","title","hasSavedOriginalTitle","async","expr","window","setImmediate","setTimeout","object","callback","prop","api","cleanUpSubscriptions","subscriptions","subscription","dispose","flagged","obj","__kv_traversed","length","runTraversal","validatables","traverseGraph","level","objValues","peek","isObservable","validatable","subscribe","graphMonitor","valueHasMutated","_destroy","collectErrors","array","errors","isInitialized","init","force","configure","group","result","computed","showAllMessages","show","isAnyMessageShown","invalidAndModifiedPresent","arrayFirst","replacements","replace","index","addRule","addAnonymousRule","ruleObj","onlyIf","condition","addExtender","ruleName","extenders","insertValidationMessage","span","document","createElement","className","parseInputValidationAttributes","valueAccessor","currentType","writeInputValidationAttributes","contexts","RegExp","source","makeBindingHandlerValidatable","handlerName","bindingHandlers","allBindingsAccessor","viewModel","bindingContext","setRules","target","definition","ruleDefinitions","targetValue","unwrappedTargetValue","nonRules","required","testVal","String","trim","minLength","normalizedVal","maxLength","step","dif","Math","abs","test","phoneNumber","otherValue","c","collection","external","externalValue","counter","arrayFilter","item","config","validationMessageElement","renderTemplate","field","applyBindingsToNode","validationMessage","validationElement","textInput","update","obsv","Error","isVisible","isCurrentlyVisible","style","display","setHtml","text","cssSettingsAccessor","css","shouldShow","hasModification","data-orig-title","newConfig","enable","validationOptions","throttleEvaluation","throttle","observableArray","clearError","h_change","h_obsValidationTrigger","read","validateObservable","_disposeValidation","removeAll","getSubscriptionsCount","_subscriptions","ruleContexts","len","localize","msgTranslations","applyBindingsWithValidation","rootNode","body","applyBindings","origApplyBindings","validatedObservable","initialValue"],"mappings":";;;;;;;;;CAUC,SAAUA,GAGgB,kBAAZC,UAA6C,gBAAZC,UAA0C,gBAAXC,QAEvEH,EAAQC,QAAQ,YAAaC,SACJ,kBAAXE,SAAyBA,OAAY,IAEnDA,QAAQ,WAAY,WAAYJ,GAGhCA,EAAQK,GAAIA,GAAGC,gBAErB,SAAWD,EAAIH,GAgqBjB,QAASK,GAAuBC,GAC5B,GAAIC,GAAoC,QAAlBD,CAEtB,OAAO,UAAUE,EAAKC,GAClB,GAAIC,EAAGC,MAAMC,WAAWJ,GACpB,OAAO,CAGX,IAAIK,GAAiBC,CACIC,UAArBN,EAAQO,UAGRF,EAAO,OACPD,EAAkBJ,IAElBK,EAAOL,EAAQO,SACfH,EAAkBJ,EAAQQ,OAKzBC,MAAML,IAAsBA,YAA2BM,QACxDL,EAAO,SAGX,IAAIM,GAAOC,EAAYC,CACvB,QAAQR,EAAKS,eACT,IAAK,OAGD,GAFAH,EAAQ,qBACRC,EAAab,EAAIgB,MAAMJ,GACJ,OAAfC,EACA,KAAM,qBAAuBf,EAAgB,+HAKjD,OAFAgB,GAAyBT,EAAgBW,MAAMJ,GAE1CE,EAIDf,EACQc,EAAW,GAAKC,EAAuB,IAEzCD,EAAW,KAAOC,EAAuB,IAAQD,EAAW,IAAMC,EAAuB,GAEvFD,EAAW,GAAKC,EAAuB,IAEzCD,EAAW,KAAOC,EAAuB,IAAQD,EAAW,IAAMC,EAAuB,IAVxF,CAcf,KAAK,QAGD,GAFAF,EAAQ,oBACRC,EAAab,EAAIgB,MAAMJ,GACJ,OAAfC,EACA,KAAM,qBA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,KAAWtC,EAAG0D,eAAgByJ,GAC9CnN,EAAGC,MAAMkG,WAAWhB,EAAMgI,IAG3B1N,EAAGsQ,cAAc1E,EAAWwE,GAI7B,IAAIG,GAAoBvQ,EAAGsQ,aAC3BtQ,GAAGsQ,cAAgB,SAAU1E,EAAWwE,GAEvC7P,EAAG+I,OAEHiH,EAAkB3E,EAAWwE,IAG9BpQ,EAAGwQ,oBAAsB,SAAUC,EAAcnQ,GAChD,IAAKC,EAAGC,MAAMuE,SAAS0L,GAAiB,MAAOzQ,GAAGwB,WAAWiP,GAAc5N,QAASgG,aAAa,GAEjG,IAAIsF,GAAOnO,EAAGwB,WAAWiP,EAgBzB,OAfAtC,GAAK/E,OAAS7I,EAAGkJ,MAAMgH,EAAcnQ,GACrC6N,EAAK9L,QAAUrC,EAAGwB,WAAoC,IAAzB2M,EAAK/E,SAASf,QAGvCrI,EAAG4I,aAAauF,EAAK/E,QACxB+E,EAAK/E,OAAON,UAAU,SAAUM,GAC9B+E,EAAK9L,QAA0B,IAAlB+G,EAAOf,UAIrBrI,EAAG2J,SAASwE,EAAK/E,QAAQN,UAAU,SAAUM,GAC5C+E,EAAK9L,QAA0B,IAAlB+G,EAAOf,UAIhB8F"} \ No newline at end of file diff --git a/Src/rules.js b/Src/rules.js index 818063f5..22feab48 100644 --- a/Src/rules.js +++ b/Src/rules.js @@ -22,16 +22,20 @@ ko.validation.rules = {}; ko.validation.rules['required'] = { validator: function (val, required) { - var stringTrimRegEx = /^\s+|\s+$/g, - testVal; + var testVal; if (val === undefined || val === null) { return !required; } testVal = val; - if (typeof (val) === "string") { - testVal = val.replace(stringTrimRegEx, ''); + if (typeof (val) === 'string') { + if (String.prototype.trim) { + testVal = val.trim(); + } + else { + testVal = val.replace(/^\s+|\s+$/g, ''); + } } if (!required) {// if they passed: { required: false }, then don't require this From a0a0fcd463998b408bc6b594727b5fb979a625ee Mon Sep 17 00:00:00 2001 From: davhdavh Date: Mon, 15 Dec 2014 18:46:08 +0700 Subject: [PATCH 111/165] Add support for observables updating the html5 attributes Closes #481 --- Dist/knockout.validation.js | 25 ++++++++++++++----------- Dist/knockout.validation.min.js | 2 +- Dist/knockout.validation.min.js.map | 2 +- Src/api.js | 25 ++++++++++++++----------- Tests/validation-ui-tests.js | 14 ++++++++++++++ 5 files changed, 44 insertions(+), 24 deletions(-) diff --git a/Dist/knockout.validation.js b/Dist/knockout.validation.js index 5045a582..00e91c58 100644 --- a/Dist/knockout.validation.js +++ b/Dist/knockout.validation.js @@ -556,7 +556,6 @@ kv.configuration = configuration; // loop through the attributes and add the information needed forEach(kv.configuration.html5Attributes, function (attr) { - var params; var ctx = koUtils.arrayFirst(contexts, function (ctx) { return ctx.rule && ctx.rule.toLowerCase() === attr.toLowerCase(); }); @@ -565,18 +564,22 @@ kv.configuration = configuration; return; } - params = ctx.params; - - // we have to do some special things for the pattern validation - if (ctx.rule === "pattern") { - if (ctx.params instanceof RegExp) { - params = ctx.params.source; // we need the pure string representation of the RegExpr without the //gi stuff - } - } - // we have a rule matching a validation attribute at this point // so lets add it to the element along with the params - element.setAttribute(attr, params); + ko.computed({ + read: function() { + var params = ko.unwrap(ctx.params); + + // we have to do some special things for the pattern validation + if (ctx.rule === "pattern" && params instanceof RegExp) { + // we need the pure string representation of the RegExpr without the //gi stuff + params = params.source; + } + + element.setAttribute(attr, params); + }, + disposeWhenNodeIsRemoved: element + }); }); contexts = null; diff --git a/Dist/knockout.validation.min.js b/Dist/knockout.validation.min.js index 57f09663..167163da 100644 --- a/Dist/knockout.validation.min.js +++ b/Dist/knockout.validation.min.js @@ -7,5 +7,5 @@ =============================================================================== */ -!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||e instanceof Date||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for week input. Should look like '2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for month input. Should look like '2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:h(c.params))?!0:(a.setError(f.formatMessage(c.message||b.message,h(c.params),a)),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,h(c.params),a)),a.__valid__(e)),void a.isValidating(!1)):void a.isValidating(!1)};b.validator(a(),h(c.params||!0),d)}if("undefined"==typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0,live:!1},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},isNumber:function(a){return!isNaN(a)},isObservableArray:function(a){return!!a&&"function"==typeof a.remove&&"function"==typeof a.removeAll&&"function"==typeof a.destroy&&"function"==typeof a.destroyAll&&"function"==typeof a.indexOf&&"function"==typeof a.replace},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return!!(a&&a.rules&&a.isValid&&a.isModified)},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},forEach:function(a,b){if(f.utils.isArray(a))return i(a,b);for(var c in a)a.hasOwnProperty(c)&&b(a[c],c)}}}();var m=function(){function b(a){i(a.subscriptions,function(a){a.dispose()}),a.subscriptions=[]}function c(a){a.options.deep&&(i(a.flagged,function(a){delete a.__kv_traversed}),a.flagged.length=0),a.options.live||b(a)}function d(a,d){d.validatables=[],b(d),e(a,d),c(d)}function e(b,c,d){var f=[],g=b.peek?b.peek():b;b.__kv_traversed!==!0&&(c.options.deep&&(b.__kv_traversed=!0,c.flagged.push(b)),d=void 0!==d?d:c.options.deep?1:-1,a.isObservable(b)&&(b.isValid||b.extend({validatable:!0}),c.validatables.push(b),c.options.live&&n.isObservableArray(b)&&c.subscriptions.push(b.subscribe(function(){c.graphMonitor.valueHasMutated()}))),g&&!g._destroy&&(n.isArray(g)?f=g:n.isObject(g)&&(f=n.values(g))),0!==d&&n.forEach(f,function(a){a&&!a.nodeType&&e(a,c,d+1)}))}function k(a){var b=[];return i(a,function(a){a.isValid()||b.push(a.error())}),b}var l=0,m=f.configuration,n=f.utils;return{init:function(a,b){l>0&&!b||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||m.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||m.errorMessageClass,j(m,a),m.registerExtenders&&f.registerExtenders(),l=1)},configure:function(a){f.init(a)},reset:f.configuration.reset,group:function(b,c){c=j(j({},m.grouping),c);var e={options:c,graphMonitor:a.observable(),flagged:[],subscriptions:[],validatables:[]},f=null;return c.observable?(d(b,e),f=a.computed(function(){return e.graphMonitor(),d(b,e),k(e.validatables)})):f=function(){return d(b,e),k(e.validatables)},f.showAllMessages=function(a){void 0===a&&(a=!0),f(),i(e.validatables,function(b){b.isModified(a)})},f.isAnyMessageShown=function(){var a=!1;return f(),a=!!g.arrayFirst(e.validatables,function(a){return!a.isValid()&&a.isModified()})},f},formatMessage:function(a,b,c){if(n.isObject(b)&&b.typeAttr&&(b=b.value),"function"==typeof a)return a(b,c);var d=h(b)||[];return n.isArray(d)||(d=[d]),a.replace(/{(\d+)}/gi,function(a,b){return"undefined"!=typeof d[b]?d[b]:a})},addRule:function(a,b){return a.extend({validatable:!0}),a.rules.push(b),a},addAnonymousRule:function(a,b){void 0===b.message&&(b.message="Error"),b.onlyIf&&(b.condition=b.onlyIf),f.addRule(a,b)},addExtender:function(b){a.extenders[b]=function(a,c){return c&&(c.message||c.onlyIf)?f.addRule(a,{rule:b,message:c.message,params:n.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(m.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=n.getConfigOptions(a).errorMessageClass,n.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(n.hasAttribute(a,c)){var d=a.getAttribute(c)||!0;if("min"===c||"max"===c){var e=a.getAttribute("type");"undefined"!=typeof e&&e||(e="text"),d={typeAttr:e,value:d}}f.addRule(b(),{rule:c,params:d})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(a,b){var c=b();if(c&&c.rules){var d=c.rules();i(f.configuration.html5Attributes,function(b){var c,e=g.arrayFirst(d,function(a){return a.rule&&a.rule.toLowerCase()===b.toLowerCase()});e&&(c=e.params,"pattern"===e.rule&&e.params instanceof RegExp&&(c=e.params.source),a.setAttribute(b,c))}),d=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var d=function(b,c){if(b&&c)for(var e in c)if(c.hasOwnProperty(e)){var g=c[e];if(b[e]){var i=b[e],j=h(i),k={},l={};for(var m in g)g.hasOwnProperty(m)&&(f.rules[m]?k[m]=g[m]:l[m]=g[m]);if(a.isObservable(i)&&i.extend(k),j&&n.isArray(j))for(var o=0;o0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}."},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address."},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date."},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[-/](?:0?[1-9]|1[012])[-/](?:0?[1-9]|[12][0-9]|3[01])$/.test(a):!0},message:"Please enter a proper date."},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number."},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit."},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number."},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal."},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(c,function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateInputElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.textInput&&f.makeBindingHandlerValidatable("textInput"),f.makeBindingHandlerValidatable("selectedOptions"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),i=(h(d),!1),j=!1;if(null===d||"undefined"==typeof d)throw new Error("Cannot bind validationMessage to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");i=d.isModified(),j=d.isValid();var k=null;(!e.messagesOnModified||i)&&(k=j?null:d.error);var l=!e.messagesOnModified||i?!j:!1,m="none"!==b.style.display;e.allowHtmlMessages?g.setHtml(b,k):a.bindingHandlers.text.update(b,function(){return k}),m&&!l?b.style.display="none":!m&&l&&(b.style.display="")}},a.bindingHandlers.validationElement={update:function(b,c,d){var e=c(),g=f.utils.getConfigOptions(b),i=(h(e),!1),j=!1;if(null===e||"undefined"==typeof e)throw new Error("Cannot bind validationElement to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!e.isValid||!e.isModified)throw new Error("Observable is not validatable");i=e.isModified(),j=e.isValid();var k=function(){var a={},b=!g.decorateElementOnModified||i?!j:!1;return a[g.errorElementClass]=b,a};a.bindingHandlers.css.update(b,k,d),g.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!g.errorsAsTitleOnModified||i,c=f.utils.getOriginalElementTitle(b);return a&&!j?{title:e.error,"data-orig-title":c}:!a||j?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){b.error(a),b.__valid__(!1)},b.clearError=function(){return b.error(null),b.__valid__(!0),b};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){b(),b.rules();return f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified.getSubscriptionsCount()>0&&(b.isModified._subscriptions.change=[]),b.isValidating.getSubscriptionsCount()>0&&(b.isValidating._subscriptions.change=[]),b.__valid__.getSubscriptionsCount()>0&&(b.__valid__._subscriptions.change=[]),g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=c.rule?f.rules[c.rule]:c,b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0},f.localize=function(a){var b;for(b in a)f.rules.hasOwnProperty(b)&&(f.rules[b].message=a[b])},a.applyBindingsWithValidation=function(b,c,d){var e,g=document.body;c&&c.nodeType?(g=c,e=d):e=c,f.init(),e&&(e=j(j({},f.configuration),e),f.utils.setDomData(g,e)),a.applyBindings(b,c)};var n=a.applyBindings;a.applyBindings=function(a,b){f.init(),n(a,b)},a.validatedObservable=function(b,c){if(!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var d=a.observable(b);return d.errors=f.group(b,c),d.isValid=a.observable(0===d.errors().length),a.isObservable(d.errors)?d.errors.subscribe(function(a){d.isValid(0===a.length)}):a.computed(d.errors).subscribe(function(a){d.isValid(0===a.length)}),d}}); +!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||e instanceof Date||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for week input. Should look like '2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for month input. Should look like '2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:h(c.params))?!0:(a.setError(f.formatMessage(c.message||b.message,h(c.params),a)),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,h(c.params),a)),a.__valid__(e)),void a.isValidating(!1)):void a.isValidating(!1)};b.validator(a(),h(c.params||!0),d)}if("undefined"==typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0,live:!1},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},isNumber:function(a){return!isNaN(a)},isObservableArray:function(a){return!!a&&"function"==typeof a.remove&&"function"==typeof a.removeAll&&"function"==typeof a.destroy&&"function"==typeof a.destroyAll&&"function"==typeof a.indexOf&&"function"==typeof a.replace},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return!!(a&&a.rules&&a.isValid&&a.isModified)},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},forEach:function(a,b){if(f.utils.isArray(a))return i(a,b);for(var c in a)a.hasOwnProperty(c)&&b(a[c],c)}}}();var m=function(){function b(a){i(a.subscriptions,function(a){a.dispose()}),a.subscriptions=[]}function c(a){a.options.deep&&(i(a.flagged,function(a){delete a.__kv_traversed}),a.flagged.length=0),a.options.live||b(a)}function d(a,d){d.validatables=[],b(d),e(a,d),c(d)}function e(b,c,d){var f=[],g=b.peek?b.peek():b;b.__kv_traversed!==!0&&(c.options.deep&&(b.__kv_traversed=!0,c.flagged.push(b)),d=void 0!==d?d:c.options.deep?1:-1,a.isObservable(b)&&(b.isValid||b.extend({validatable:!0}),c.validatables.push(b),c.options.live&&n.isObservableArray(b)&&c.subscriptions.push(b.subscribe(function(){c.graphMonitor.valueHasMutated()}))),g&&!g._destroy&&(n.isArray(g)?f=g:n.isObject(g)&&(f=n.values(g))),0!==d&&n.forEach(f,function(a){a&&!a.nodeType&&e(a,c,d+1)}))}function k(a){var b=[];return i(a,function(a){a.isValid()||b.push(a.error())}),b}var l=0,m=f.configuration,n=f.utils;return{init:function(a,b){l>0&&!b||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||m.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||m.errorMessageClass,j(m,a),m.registerExtenders&&f.registerExtenders(),l=1)},configure:function(a){f.init(a)},reset:f.configuration.reset,group:function(b,c){c=j(j({},m.grouping),c);var e={options:c,graphMonitor:a.observable(),flagged:[],subscriptions:[],validatables:[]},f=null;return c.observable?(d(b,e),f=a.computed(function(){return e.graphMonitor(),d(b,e),k(e.validatables)})):f=function(){return d(b,e),k(e.validatables)},f.showAllMessages=function(a){void 0===a&&(a=!0),f(),i(e.validatables,function(b){b.isModified(a)})},f.isAnyMessageShown=function(){var a=!1;return f(),a=!!g.arrayFirst(e.validatables,function(a){return!a.isValid()&&a.isModified()})},f},formatMessage:function(a,b,c){if(n.isObject(b)&&b.typeAttr&&(b=b.value),"function"==typeof a)return a(b,c);var d=h(b)||[];return n.isArray(d)||(d=[d]),a.replace(/{(\d+)}/gi,function(a,b){return"undefined"!=typeof d[b]?d[b]:a})},addRule:function(a,b){return a.extend({validatable:!0}),a.rules.push(b),a},addAnonymousRule:function(a,b){void 0===b.message&&(b.message="Error"),b.onlyIf&&(b.condition=b.onlyIf),f.addRule(a,b)},addExtender:function(b){a.extenders[b]=function(a,c){return c&&(c.message||c.onlyIf)?f.addRule(a,{rule:b,message:c.message,params:n.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(m.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=n.getConfigOptions(a).errorMessageClass,n.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(n.hasAttribute(a,c)){var d=a.getAttribute(c)||!0;if("min"===c||"max"===c){var e=a.getAttribute("type");"undefined"!=typeof e&&e||(e="text"),d={typeAttr:e,value:d}}f.addRule(b(),{rule:c,params:d})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(b,c){var d=c();if(d&&d.rules){var e=d.rules();i(f.configuration.html5Attributes,function(c){var d=g.arrayFirst(e,function(a){return a.rule&&a.rule.toLowerCase()===c.toLowerCase()});d&&a.computed({read:function(){var e=a.unwrap(d.params);"pattern"===d.rule&&e instanceof RegExp&&(e=e.source),b.setAttribute(c,e)},disposeWhenNodeIsRemoved:b})}),e=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var d=function(b,c){if(b&&c)for(var e in c)if(c.hasOwnProperty(e)){var g=c[e];if(b[e]){var i=b[e],j=h(i),k={},l={};for(var m in g)g.hasOwnProperty(m)&&(f.rules[m]?k[m]=g[m]:l[m]=g[m]);if(a.isObservable(i)&&i.extend(k),j&&n.isArray(j))for(var o=0;o0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}."},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address."},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date."},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[-/](?:0?[1-9]|1[012])[-/](?:0?[1-9]|[12][0-9]|3[01])$/.test(a):!0},message:"Please enter a proper date."},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number."},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit."},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number."},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal."},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(c,function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateInputElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.textInput&&f.makeBindingHandlerValidatable("textInput"),f.makeBindingHandlerValidatable("selectedOptions"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),i=(h(d),!1),j=!1;if(null===d||"undefined"==typeof d)throw new Error("Cannot bind validationMessage to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");i=d.isModified(),j=d.isValid();var k=null;(!e.messagesOnModified||i)&&(k=j?null:d.error);var l=!e.messagesOnModified||i?!j:!1,m="none"!==b.style.display;e.allowHtmlMessages?g.setHtml(b,k):a.bindingHandlers.text.update(b,function(){return k}),m&&!l?b.style.display="none":!m&&l&&(b.style.display="")}},a.bindingHandlers.validationElement={update:function(b,c,d){var e=c(),g=f.utils.getConfigOptions(b),i=(h(e),!1),j=!1;if(null===e||"undefined"==typeof e)throw new Error("Cannot bind validationElement to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!e.isValid||!e.isModified)throw new Error("Observable is not validatable");i=e.isModified(),j=e.isValid();var k=function(){var a={},b=!g.decorateElementOnModified||i?!j:!1;return a[g.errorElementClass]=b,a};a.bindingHandlers.css.update(b,k,d),g.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!g.errorsAsTitleOnModified||i,c=f.utils.getOriginalElementTitle(b);return a&&!j?{title:e.error,"data-orig-title":c}:!a||j?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){b.error(a),b.__valid__(!1)},b.clearError=function(){return b.error(null),b.__valid__(!0),b};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){b(),b.rules();return f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified.getSubscriptionsCount()>0&&(b.isModified._subscriptions.change=[]),b.isValidating.getSubscriptionsCount()>0&&(b.isValidating._subscriptions.change=[]),b.__valid__.getSubscriptionsCount()>0&&(b.__valid__._subscriptions.change=[]),g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=c.rule?f.rules[c.rule]:c,b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0},f.localize=function(a){var b;for(b in a)f.rules.hasOwnProperty(b)&&(f.rules[b].message=a[b])},a.applyBindingsWithValidation=function(b,c,d){var e,g=document.body;c&&c.nodeType?(g=c,e=d):e=c,f.init(),e&&(e=j(j({},f.configuration),e),f.utils.setDomData(g,e)),a.applyBindings(b,c)};var n=a.applyBindings;a.applyBindings=function(a,b){f.init(),n(a,b)},a.validatedObservable=function(b,c){if(!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var d=a.observable(b);return d.errors=f.group(b,c),d.isValid=a.observable(0===d.errors().length),a.isObservable(d.errors)?d.errors.subscribe(function(a){d.isValid(0===a.length)}):a.computed(d.errors).subscribe(function(a){d.isValid(0===a.length)}),d}}); //# sourceMappingURL=knockout.validation.min.js.map \ No newline at end of file diff --git a/Dist/knockout.validation.min.js.map b/Dist/knockout.validation.min.js.map index 080cb3eb..6a9af96f 100644 --- a/Dist/knockout.validation.min.js.map +++ b/Dist/knockout.validation.min.js.map @@ -1 +1 @@ -{"version":3,"file":"knockout.validation.min.js","sources":["knockout.validation.js"],"names":["factory","require","exports","module","define","ko","validation","minMaxValidatorFactory","validatorName","isMaxValidation","val","options","kv","utils","isEmptyVal","comparisonValue","type","undefined","typeAttr","value","isNaN","Date","regex","valMatches","comparisonValueMatches","toLowerCase","match","parseFloat","validateSync","observable","rule","ctx","validator","params","unwrap","setError","formatMessage","message","validateAsync","isValidating","callBack","valObj","isValid","msg","__valid__","error","koUtils","unwrapObservable","forEach","arrayForEach","extend","defaults","registerExtenders","messagesOnModified","errorsAsTitle","errorsAsTitleOnModified","messageTemplate","insertMessages","parseInputAttributes","writeInputAttributes","decorateInputElement","decorateElementOnModified","errorClass","errorElementClass","errorMessageClass","allowHtmlMessages","grouping","deep","live","validate","configuration","html5Attributes","html5InputTypes","reset","seedId","getTime","domData","domDataKey","isArray","o","Object","prototype","toString","call","isObject","isNumber","isObservableArray","instance","values","r","i","hasOwnProperty","push","getValue","hasAttribute","node","attr","getAttribute","element","setAttribute","isValidatable","rules","isModified","insertAfter","newNode","parentNode","insertBefore","nextSibling","newId","getConfigOptions","contextFor","setDomData","data","key","getDomData","nodeType","context","getOriginalElementTitle","savedOriginalTitle","currentTitle","title","hasSavedOriginalTitle","async","expr","window","setImmediate","setTimeout","object","callback","prop","api","cleanUpSubscriptions","subscriptions","subscription","dispose","flagged","obj","__kv_traversed","length","runTraversal","validatables","traverseGraph","level","objValues","peek","isObservable","validatable","subscribe","graphMonitor","valueHasMutated","_destroy","collectErrors","array","errors","isInitialized","init","force","configure","group","result","computed","showAllMessages","show","isAnyMessageShown","invalidAndModifiedPresent","arrayFirst","replacements","replace","index","addRule","addAnonymousRule","ruleObj","onlyIf","condition","addExtender","ruleName","extenders","insertValidationMessage","span","document","createElement","className","parseInputValidationAttributes","valueAccessor","currentType","writeInputValidationAttributes","contexts","RegExp","source","makeBindingHandlerValidatable","handlerName","bindingHandlers","allBindingsAccessor","viewModel","bindingContext","setRules","target","definition","ruleDefinitions","targetValue","unwrappedTargetValue","nonRules","required","testVal","String","trim","minLength","normalizedVal","maxLength","step","dif","Math","abs","test","phoneNumber","otherValue","c","collection","external","externalValue","counter","arrayFilter","item","config","validationMessageElement","renderTemplate","field","applyBindingsToNode","validationMessage","validationElement","textInput","update","obsv","Error","isVisible","isCurrentlyVisible","style","display","setHtml","text","cssSettingsAccessor","css","shouldShow","hasModification","data-orig-title","newConfig","enable","validationOptions","throttleEvaluation","throttle","observableArray","clearError","h_change","h_obsValidationTrigger","read","validateObservable","_disposeValidation","removeAll","getSubscriptionsCount","_subscriptions","ruleContexts","len","localize","msgTranslations","applyBindingsWithValidation","rootNode","body","applyBindings","origApplyBindings","validatedObservable","initialValue"],"mappings":";;;;;;;;;CAUC,SAAUA,GAGgB,kBAAZC,UAA6C,gBAAZC,UAA0C,gBAAXC,QAEvEH,EAAQC,QAAQ,YAAaC,SACJ,kBAAXE,SAAyBA,OAAY,IAEnDA,QAAQ,WAAY,WAAYJ,GAGhCA,EAAQK,GAAIA,GAAGC,gBAErB,SAAWD,EAAIH,GA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,GACrC6N,EAAK9L,QAAUrC,EAAGwB,WAAoC,IAAzB2M,EAAK/E,SAASf,QAGvCrI,EAAG4I,aAAauF,EAAK/E,QACxB+E,EAAK/E,OAAON,UAAU,SAAUM,GAC9B+E,EAAK9L,QAA0B,IAAlB+G,EAAOf,UAIrBrI,EAAG2J,SAASwE,EAAK/E,QAAQN,UAAU,SAAUM,GAC5C+E,EAAK9L,QAA0B,IAAlB+G,EAAOf,UAIhB8F"} \ No newline at end of file +{"version":3,"file":"knockout.validation.min.js","sources":["knockout.validation.js"],"names":["factory","require","exports","module","define","ko","validation","minMaxValidatorFactory","validatorName","isMaxValidation","val","options","kv","utils","isEmptyVal","comparisonValue","type","undefined","typeAttr","value","isNaN","Date","regex","valMatches","comparisonValueMatches","toLowerCase","match","parseFloat","validateSync","observable","rule","ctx","validator","params","unwrap","setError","formatMessage","message","validateAsync","isValidating","callBack","valObj","isValid","msg","__valid__","error","koUtils","unwrapObservable","forEach","arrayForEach","extend","defaults","registerExtenders","messagesOnModified","errorsAsTitle","errorsAsTitleOnModified","messageTemplate","insertMessages","parseInputAttributes","writeInputAttributes","decorateInputElement","decorateElementOnModified","errorClass","errorElementClass","errorMessageClass","allowHtmlMessages","grouping","deep","live","validate","configuration","html5Attributes","html5InputTypes","reset","seedId","getTime","domData","domDataKey","isArray","o","Object","prototype","toString","call","isObject","isNumber","isObservableArray","instance","values","r","i","hasOwnProperty","push","getValue","hasAttribute","node","attr","getAttribute","element","setAttribute","isValidatable","rules","isModified","insertAfter","newNode","parentNode","insertBefore","nextSibling","newId","getConfigOptions","contextFor","setDomData","data","key","getDomData","nodeType","context","getOriginalElementTitle","savedOriginalTitle","currentTitle","title","hasSavedOriginalTitle","async","expr","window","setImmediate","setTimeout","object","callback","prop","api","cleanUpSubscriptions","subscriptions","subscription","dispose","flagged","obj","__kv_traversed","length","runTraversal","validatables","traverseGraph","level","objValues","peek","isObservable","validatable","subscribe","graphMonitor","valueHasMutated","_destroy","collectErrors","array","errors","isInitialized","init","force","configure","group","result","computed","showAllMessages","show","isAnyMessageShown","invalidAndModifiedPresent","arrayFirst","replacements","replace","index","addRule","addAnonymousRule","ruleObj","onlyIf","condition","addExtender","ruleName","extenders","insertValidationMessage","span","document","createElement","className","parseInputValidationAttributes","valueAccessor","currentType","writeInputValidationAttributes","contexts","read","RegExp","source","disposeWhenNodeIsRemoved","makeBindingHandlerValidatable","handlerName","bindingHandlers","allBindingsAccessor","viewModel","bindingContext","setRules","target","definition","ruleDefinitions","targetValue","unwrappedTargetValue","nonRules","required","testVal","String","trim","minLength","normalizedVal","maxLength","step","dif","Math","abs","test","phoneNumber","otherValue","c","collection","external","externalValue","counter","arrayFilter","item","config","validationMessageElement","renderTemplate","field","applyBindingsToNode","validationMessage","validationElement","textInput","update","obsv","Error","isVisible","isCurrentlyVisible","style","display","setHtml","text","cssSettingsAccessor","css","shouldShow","hasModification","data-orig-title","newConfig","enable","validationOptions","throttleEvaluation","throttle","observableArray","clearError","h_change","h_obsValidationTrigger","validateObservable","_disposeValidation","removeAll","getSubscriptionsCount","_subscriptions","ruleContexts","len","localize","msgTranslations","applyBindingsWithValidation","rootNode","body","applyBindings","origApplyBindings","validatedObservable","initialValue"],"mappings":";;;;;;;;;CAUC,SAAUA,GAGgB,kBAAZC,UAA6C,gBAAZC,UAA0C,gBAAXC,QAEvEH,EAAQC,QAAQ,YAAaC,SACJ,kBAAXE,SAAyBA,OAAY,IAEnDA,QAAQ,WAAY,WAAYJ,GAGhCA,EAAQK,GAAIA,GAAGC,gBAErB,SAAWD,EAAIH,GAmqBjB,QAASK,GAAuBC,GAC5B,GAAIC,GAAoC,QAAlBD,CAEtB,OAAO,UAAUE,EAAKC,GAClB,GAAIC,EAAGC,MAAMC,WAAWJ,GACpB,OAAO,CAGX,IAAIK,GAAiBC,CACIC,UAArBN,EAAQO,UAGRF,EAAO,OACPD,EAAkBJ,IAElBK,EAAOL,EAAQO,SACfH,EAAkBJ,EAAQQ,OAKzBC,MAAML,IAAsBA,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KjF,QAAQN,UAAU,SAAUM,GAC5CiF,EAAKhM,QAA0B,IAAlB+G,EAAOf,UAIhBgG"} \ No newline at end of file diff --git a/Src/api.js b/Src/api.js index 247c9feb..4901e390 100644 --- a/Src/api.js +++ b/Src/api.js @@ -360,7 +360,6 @@ // loop through the attributes and add the information needed ko.utils.arrayForEach(ko.validation.configuration.html5Attributes, function (attr) { - var params; var ctx = ko.utils.arrayFirst(contexts, function (ctx) { return ctx.rule && ctx.rule.toLowerCase() === attr.toLowerCase(); }); @@ -369,18 +368,22 @@ return; } - params = ctx.params; - - // we have to do some special things for the pattern validation - if (ctx.rule === "pattern") { - if (ctx.params instanceof RegExp) { - params = ctx.params.source; // we need the pure string representation of the RegExpr without the //gi stuff - } - } - // we have a rule matching a validation attribute at this point // so lets add it to the element along with the params - element.setAttribute(attr, params); + ko.computed({ + read: function() { + var params = ko.unwrap(ctx.params); + + // we have to do some special things for the pattern validation + if (ctx.rule === "pattern" && params instanceof RegExp) { + // we need the pure string representation of the RegExpr without the //gi stuff + params = params.source; + } + + element.setAttribute(attr, params); + }, + disposeWhenNodeIsRemoved: element + }); }); contexts = null; diff --git a/Tests/validation-ui-tests.js b/Tests/validation-ui-tests.js index 01845324..17c8d6d5 100644 --- a/Tests/validation-ui-tests.js +++ b/Tests/validation-ui-tests.js @@ -571,6 +571,20 @@ QUnit.test('Issue #44 - Validation Element - Is Invalid Test', function(assert) }); +QUnit.test('Issue #481 - writeInputAttributes doesn\'t unwrap params to sync attribute', function(assert) { + var minValue = ko.observable(4); + var testObj = ko.observable(10).extend({min: minValue}); + + var $element = jQuery(''); + addTestHtml($element); + ko.validation.init({writeInputAttributes: true}, true); + applyTestBindings({value: testObj}); + + assert.strictEqual($element.attr('min'), '4', 'min attribute is written'); + minValue(15); + assert.strictEqual($element.attr('min'), '15', 'min attribute is written'); +}); + QUnit.test('Issue #80 - Write HTML5 Validation Attributes programmatically', function(assert) { var vm = { From 9bf20ed44ade757b41f4e3676bb177d131ab7240 Mon Sep 17 00:00:00 2001 From: crissdev Date: Fri, 19 Dec 2014 01:01:26 +0200 Subject: [PATCH 112/165] Fix #472 - applyBindingsWithValidation fails when invoked with viewModel and options Added tests to prevent future bugs and to verify implementation. --- Src/ko.extensions.js | 2 +- Tests/api-tests.js | 112 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 113 insertions(+), 1 deletion(-) diff --git a/Src/ko.extensions.js b/Src/ko.extensions.js index 6382d0d7..e3de4260 100644 --- a/Src/ko.extensions.js +++ b/Src/ko.extensions.js @@ -24,7 +24,7 @@ ko.applyBindingsWithValidation = function (viewModel, rootNode, options) { ko.validation.utils.setDomData(node, config); } - ko.applyBindings(viewModel, rootNode); + ko.applyBindings(viewModel, node); }; //override the original applyBindings so that we can ensure all new rules and what not are correctly registered diff --git a/Tests/api-tests.js b/Tests/api-tests.js index 09bb71b0..d09708ed 100644 --- a/Tests/api-tests.js +++ b/Tests/api-tests.js @@ -553,3 +553,115 @@ QUnit.test('formatMessage may use multiple replacements', function(assert) { var result = ko.validation.formatMessage(message, params, obsv); assert.equal(result, 'Value must be between 1 and 5.'); }); + + +QUnit.module('applyBindingsWithValidation Tests'); + +QUnit.test('can be invoked with (viewModel)', function(assert) { + assert.expect(2); + + ko.validation.init({}, true); + + var _applyBindings = ko.applyBindings; + var _setDomData = ko.validation.utils.setDomData; + + var viewModel = {}; + + ko.validation.utils.setDomData = function(/*node, data*/) { + // We don't expect a call to setDomData when no options are provided to applyBindingsWithValidation + assert.ok(false, 'Unexpected setDomData call'); + }; + ko.applyBindings = function(viewModelOrBindingContext, rootNode) { + assert.strictEqual(viewModelOrBindingContext, viewModel, 'viewModelOrBindingContext is correct'); + assert.strictEqual(rootNode, document.body, 'rootNode is correct'); + }; + + ko.applyBindingsWithValidation(viewModel); + + // Restore methods + ko.applyBindings = _applyBindings; + ko.validation.utils.setDomData = _setDomData; +}); + +QUnit.test('can be invoked with (viewModel, options)', function(assert) { + assert.expect(4); + + ko.validation.init({}, true); + + var _applyBindings = ko.applyBindings; + var _setDomData = ko.validation.utils.setDomData; + + var viewModel = {}; + var options = ko.utils.extend(ko.utils.extend({}, ko.validation.configuration), {messageTemplate: ''}); + + ko.validation.utils.setDomData = function(node, data) { + assert.strictEqual(node, document.body, 'rootNode is correct'); + assert.propEqual(data, options, 'data is correct'); + }; + ko.applyBindings = function(viewModelOrBindingContext, rootNode) { + assert.strictEqual(viewModelOrBindingContext, viewModel, 'viewModelOrBindingContext is correct'); + assert.strictEqual(rootNode, document.body, 'rootNode is correct'); + }; + + ko.applyBindingsWithValidation(viewModel, {messageTemplate: ''}); + + // Restore methods + ko.applyBindings = _applyBindings; + ko.validation.utils.setDomData = _setDomData; +}); + +QUnit.test('can be invoked with (viewModel, rootNode)', function(assert) { + assert.expect(2); + + ko.validation.init({}, true); + + var _applyBindings = ko.applyBindings; + var _setDomData = ko.validation.utils.setDomData; + + var viewModel = {}; + var element = document.createElement('div'); + + ko.validation.utils.setDomData = function(/*node, data*/) { + // We don't expect a call to setDomData when no options are provided to applyBindingsWithValidation + assert.ok(false, 'Unexpected setDomData call'); + }; + + ko.applyBindings = function(viewModelOrBindingContext, rootNode) { + assert.strictEqual(viewModelOrBindingContext, viewModel, 'viewModelOrBindingContext is correct'); + assert.strictEqual(rootNode, element, 'rootNode is correct'); + }; + + ko.applyBindingsWithValidation(viewModel, element); + + // Restore methods + ko.applyBindings = _applyBindings; + ko.validation.utils.setDomData = _setDomData; +}); + +QUnit.test('can be invoked with (viewModel, rootNode, options)', function(assert) { + + ko.validation.init({}, true); + + var _applyBindings = ko.applyBindings; + var _setDomData = ko.validation.utils.setDomData; + + var viewModel = {}; + var element = document.createElement('div'); + var options = ko.utils.extend(ko.utils.extend({}, ko.validation.configuration), {messageTemplate: ''}); + + ko.validation.utils.setDomData = function(node, data) { + assert.strictEqual(node, element, 'node is correct'); + assert.propEqual(data, options, 'data is correct'); + }; + ko.applyBindings = function(viewModelOrBindingContext, rootNode) { + assert.strictEqual(viewModelOrBindingContext, viewModel, 'viewModelOrBindingContext is correct'); + assert.strictEqual(rootNode, element, 'rootNode is correct'); + }; + + ko.applyBindingsWithValidation(viewModel, element, {messageTemplate: ''}); + + // Restore methods + ko.applyBindings = _applyBindings; + ko.validation.utils.setDomData = _setDomData; +}); + From 16061a721f337fa0b0afd8ec157e43e1d7650253 Mon Sep 17 00:00:00 2001 From: crissdev Date: Fri, 19 Dec 2014 01:11:11 +0200 Subject: [PATCH 113/165] Rebuild distributables --- Dist/knockout.validation.js | 2 +- Dist/knockout.validation.min.js | 2 +- Dist/knockout.validation.min.js.map | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Dist/knockout.validation.js b/Dist/knockout.validation.js index 00e91c58..b096a81d 100644 --- a/Dist/knockout.validation.js +++ b/Dist/knockout.validation.js @@ -1362,7 +1362,7 @@ ko.applyBindingsWithValidation = function (viewModel, rootNode, options) { kv.utils.setDomData(node, config); } - ko.applyBindings(viewModel, rootNode); + ko.applyBindings(viewModel, node); }; //override the original applyBindings so that we can ensure all new rules and what not are correctly registered diff --git a/Dist/knockout.validation.min.js b/Dist/knockout.validation.min.js index 167163da..5272033e 100644 --- a/Dist/knockout.validation.min.js +++ b/Dist/knockout.validation.min.js @@ -7,5 +7,5 @@ =============================================================================== */ -!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||e instanceof Date||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for week input. Should look like '2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for month input. Should look like '2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:h(c.params))?!0:(a.setError(f.formatMessage(c.message||b.message,h(c.params),a)),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,h(c.params),a)),a.__valid__(e)),void a.isValidating(!1)):void a.isValidating(!1)};b.validator(a(),h(c.params||!0),d)}if("undefined"==typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0,live:!1},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},isNumber:function(a){return!isNaN(a)},isObservableArray:function(a){return!!a&&"function"==typeof a.remove&&"function"==typeof a.removeAll&&"function"==typeof a.destroy&&"function"==typeof a.destroyAll&&"function"==typeof a.indexOf&&"function"==typeof a.replace},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return!!(a&&a.rules&&a.isValid&&a.isModified)},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},forEach:function(a,b){if(f.utils.isArray(a))return i(a,b);for(var c in a)a.hasOwnProperty(c)&&b(a[c],c)}}}();var m=function(){function b(a){i(a.subscriptions,function(a){a.dispose()}),a.subscriptions=[]}function c(a){a.options.deep&&(i(a.flagged,function(a){delete a.__kv_traversed}),a.flagged.length=0),a.options.live||b(a)}function d(a,d){d.validatables=[],b(d),e(a,d),c(d)}function e(b,c,d){var f=[],g=b.peek?b.peek():b;b.__kv_traversed!==!0&&(c.options.deep&&(b.__kv_traversed=!0,c.flagged.push(b)),d=void 0!==d?d:c.options.deep?1:-1,a.isObservable(b)&&(b.isValid||b.extend({validatable:!0}),c.validatables.push(b),c.options.live&&n.isObservableArray(b)&&c.subscriptions.push(b.subscribe(function(){c.graphMonitor.valueHasMutated()}))),g&&!g._destroy&&(n.isArray(g)?f=g:n.isObject(g)&&(f=n.values(g))),0!==d&&n.forEach(f,function(a){a&&!a.nodeType&&e(a,c,d+1)}))}function k(a){var b=[];return i(a,function(a){a.isValid()||b.push(a.error())}),b}var l=0,m=f.configuration,n=f.utils;return{init:function(a,b){l>0&&!b||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||m.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||m.errorMessageClass,j(m,a),m.registerExtenders&&f.registerExtenders(),l=1)},configure:function(a){f.init(a)},reset:f.configuration.reset,group:function(b,c){c=j(j({},m.grouping),c);var e={options:c,graphMonitor:a.observable(),flagged:[],subscriptions:[],validatables:[]},f=null;return c.observable?(d(b,e),f=a.computed(function(){return e.graphMonitor(),d(b,e),k(e.validatables)})):f=function(){return d(b,e),k(e.validatables)},f.showAllMessages=function(a){void 0===a&&(a=!0),f(),i(e.validatables,function(b){b.isModified(a)})},f.isAnyMessageShown=function(){var a=!1;return f(),a=!!g.arrayFirst(e.validatables,function(a){return!a.isValid()&&a.isModified()})},f},formatMessage:function(a,b,c){if(n.isObject(b)&&b.typeAttr&&(b=b.value),"function"==typeof a)return a(b,c);var d=h(b)||[];return n.isArray(d)||(d=[d]),a.replace(/{(\d+)}/gi,function(a,b){return"undefined"!=typeof d[b]?d[b]:a})},addRule:function(a,b){return a.extend({validatable:!0}),a.rules.push(b),a},addAnonymousRule:function(a,b){void 0===b.message&&(b.message="Error"),b.onlyIf&&(b.condition=b.onlyIf),f.addRule(a,b)},addExtender:function(b){a.extenders[b]=function(a,c){return c&&(c.message||c.onlyIf)?f.addRule(a,{rule:b,message:c.message,params:n.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(m.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=n.getConfigOptions(a).errorMessageClass,n.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(n.hasAttribute(a,c)){var d=a.getAttribute(c)||!0;if("min"===c||"max"===c){var e=a.getAttribute("type");"undefined"!=typeof e&&e||(e="text"),d={typeAttr:e,value:d}}f.addRule(b(),{rule:c,params:d})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(b,c){var d=c();if(d&&d.rules){var e=d.rules();i(f.configuration.html5Attributes,function(c){var d=g.arrayFirst(e,function(a){return a.rule&&a.rule.toLowerCase()===c.toLowerCase()});d&&a.computed({read:function(){var e=a.unwrap(d.params);"pattern"===d.rule&&e instanceof RegExp&&(e=e.source),b.setAttribute(c,e)},disposeWhenNodeIsRemoved:b})}),e=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var d=function(b,c){if(b&&c)for(var e in c)if(c.hasOwnProperty(e)){var g=c[e];if(b[e]){var i=b[e],j=h(i),k={},l={};for(var m in g)g.hasOwnProperty(m)&&(f.rules[m]?k[m]=g[m]:l[m]=g[m]);if(a.isObservable(i)&&i.extend(k),j&&n.isArray(j))for(var o=0;o0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}."},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address."},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date."},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[-/](?:0?[1-9]|1[012])[-/](?:0?[1-9]|[12][0-9]|3[01])$/.test(a):!0},message:"Please enter a proper date."},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number."},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit."},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number."},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal."},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(c,function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateInputElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.textInput&&f.makeBindingHandlerValidatable("textInput"),f.makeBindingHandlerValidatable("selectedOptions"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),i=(h(d),!1),j=!1;if(null===d||"undefined"==typeof d)throw new Error("Cannot bind validationMessage to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");i=d.isModified(),j=d.isValid();var k=null;(!e.messagesOnModified||i)&&(k=j?null:d.error);var l=!e.messagesOnModified||i?!j:!1,m="none"!==b.style.display;e.allowHtmlMessages?g.setHtml(b,k):a.bindingHandlers.text.update(b,function(){return k}),m&&!l?b.style.display="none":!m&&l&&(b.style.display="")}},a.bindingHandlers.validationElement={update:function(b,c,d){var e=c(),g=f.utils.getConfigOptions(b),i=(h(e),!1),j=!1;if(null===e||"undefined"==typeof e)throw new Error("Cannot bind validationElement to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!e.isValid||!e.isModified)throw new Error("Observable is not validatable");i=e.isModified(),j=e.isValid();var k=function(){var a={},b=!g.decorateElementOnModified||i?!j:!1;return a[g.errorElementClass]=b,a};a.bindingHandlers.css.update(b,k,d),g.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!g.errorsAsTitleOnModified||i,c=f.utils.getOriginalElementTitle(b);return a&&!j?{title:e.error,"data-orig-title":c}:!a||j?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){b.error(a),b.__valid__(!1)},b.clearError=function(){return b.error(null),b.__valid__(!0),b};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){b(),b.rules();return f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified.getSubscriptionsCount()>0&&(b.isModified._subscriptions.change=[]),b.isValidating.getSubscriptionsCount()>0&&(b.isValidating._subscriptions.change=[]),b.__valid__.getSubscriptionsCount()>0&&(b.__valid__._subscriptions.change=[]),g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=c.rule?f.rules[c.rule]:c,b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0},f.localize=function(a){var b;for(b in a)f.rules.hasOwnProperty(b)&&(f.rules[b].message=a[b])},a.applyBindingsWithValidation=function(b,c,d){var e,g=document.body;c&&c.nodeType?(g=c,e=d):e=c,f.init(),e&&(e=j(j({},f.configuration),e),f.utils.setDomData(g,e)),a.applyBindings(b,c)};var n=a.applyBindings;a.applyBindings=function(a,b){f.init(),n(a,b)},a.validatedObservable=function(b,c){if(!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var d=a.observable(b);return d.errors=f.group(b,c),d.isValid=a.observable(0===d.errors().length),a.isObservable(d.errors)?d.errors.subscribe(function(a){d.isValid(0===a.length)}):a.computed(d.errors).subscribe(function(a){d.isValid(0===a.length)}),d}}); +!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||e instanceof Date||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for week input. Should look like '2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for month input. Should look like '2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:h(c.params))?!0:(a.setError(f.formatMessage(c.message||b.message,h(c.params),a)),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,h(c.params),a)),a.__valid__(e)),void a.isValidating(!1)):void a.isValidating(!1)};b.validator(a(),h(c.params||!0),d)}if("undefined"==typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0,live:!1},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},isNumber:function(a){return!isNaN(a)},isObservableArray:function(a){return!!a&&"function"==typeof a.remove&&"function"==typeof a.removeAll&&"function"==typeof a.destroy&&"function"==typeof a.destroyAll&&"function"==typeof a.indexOf&&"function"==typeof a.replace},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return!!(a&&a.rules&&a.isValid&&a.isModified)},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},forEach:function(a,b){if(f.utils.isArray(a))return i(a,b);for(var c in a)a.hasOwnProperty(c)&&b(a[c],c)}}}();var m=function(){function b(a){i(a.subscriptions,function(a){a.dispose()}),a.subscriptions=[]}function c(a){a.options.deep&&(i(a.flagged,function(a){delete a.__kv_traversed}),a.flagged.length=0),a.options.live||b(a)}function d(a,d){d.validatables=[],b(d),e(a,d),c(d)}function e(b,c,d){var f=[],g=b.peek?b.peek():b;b.__kv_traversed!==!0&&(c.options.deep&&(b.__kv_traversed=!0,c.flagged.push(b)),d=void 0!==d?d:c.options.deep?1:-1,a.isObservable(b)&&(b.isValid||b.extend({validatable:!0}),c.validatables.push(b),c.options.live&&n.isObservableArray(b)&&c.subscriptions.push(b.subscribe(function(){c.graphMonitor.valueHasMutated()}))),g&&!g._destroy&&(n.isArray(g)?f=g:n.isObject(g)&&(f=n.values(g))),0!==d&&n.forEach(f,function(a){a&&!a.nodeType&&e(a,c,d+1)}))}function k(a){var b=[];return i(a,function(a){a.isValid()||b.push(a.error())}),b}var l=0,m=f.configuration,n=f.utils;return{init:function(a,b){l>0&&!b||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||m.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||m.errorMessageClass,j(m,a),m.registerExtenders&&f.registerExtenders(),l=1)},configure:function(a){f.init(a)},reset:f.configuration.reset,group:function(b,c){c=j(j({},m.grouping),c);var e={options:c,graphMonitor:a.observable(),flagged:[],subscriptions:[],validatables:[]},f=null;return c.observable?(d(b,e),f=a.computed(function(){return e.graphMonitor(),d(b,e),k(e.validatables)})):f=function(){return d(b,e),k(e.validatables)},f.showAllMessages=function(a){void 0===a&&(a=!0),f(),i(e.validatables,function(b){b.isModified(a)})},f.isAnyMessageShown=function(){var a=!1;return f(),a=!!g.arrayFirst(e.validatables,function(a){return!a.isValid()&&a.isModified()})},f},formatMessage:function(a,b,c){if(n.isObject(b)&&b.typeAttr&&(b=b.value),"function"==typeof a)return a(b,c);var d=h(b)||[];return n.isArray(d)||(d=[d]),a.replace(/{(\d+)}/gi,function(a,b){return"undefined"!=typeof d[b]?d[b]:a})},addRule:function(a,b){return a.extend({validatable:!0}),a.rules.push(b),a},addAnonymousRule:function(a,b){void 0===b.message&&(b.message="Error"),b.onlyIf&&(b.condition=b.onlyIf),f.addRule(a,b)},addExtender:function(b){a.extenders[b]=function(a,c){return c&&(c.message||c.onlyIf)?f.addRule(a,{rule:b,message:c.message,params:n.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(m.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=n.getConfigOptions(a).errorMessageClass,n.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(n.hasAttribute(a,c)){var d=a.getAttribute(c)||!0;if("min"===c||"max"===c){var e=a.getAttribute("type");"undefined"!=typeof e&&e||(e="text"),d={typeAttr:e,value:d}}f.addRule(b(),{rule:c,params:d})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(b,c){var d=c();if(d&&d.rules){var e=d.rules();i(f.configuration.html5Attributes,function(c){var d=g.arrayFirst(e,function(a){return a.rule&&a.rule.toLowerCase()===c.toLowerCase()});d&&a.computed({read:function(){var e=a.unwrap(d.params);"pattern"===d.rule&&e instanceof RegExp&&(e=e.source),b.setAttribute(c,e)},disposeWhenNodeIsRemoved:b})}),e=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var d=function(b,c){if(b&&c)for(var e in c)if(c.hasOwnProperty(e)){var g=c[e];if(b[e]){var i=b[e],j=h(i),k={},l={};for(var m in g)g.hasOwnProperty(m)&&(f.rules[m]?k[m]=g[m]:l[m]=g[m]);if(a.isObservable(i)&&i.extend(k),j&&n.isArray(j))for(var o=0;o0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}."},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address."},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date."},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[-/](?:0?[1-9]|1[012])[-/](?:0?[1-9]|[12][0-9]|3[01])$/.test(a):!0},message:"Please enter a proper date."},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number."},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit."},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number."},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal."},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(c,function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateInputElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.textInput&&f.makeBindingHandlerValidatable("textInput"),f.makeBindingHandlerValidatable("selectedOptions"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),i=(h(d),!1),j=!1;if(null===d||"undefined"==typeof d)throw new Error("Cannot bind validationMessage to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");i=d.isModified(),j=d.isValid();var k=null;(!e.messagesOnModified||i)&&(k=j?null:d.error);var l=!e.messagesOnModified||i?!j:!1,m="none"!==b.style.display;e.allowHtmlMessages?g.setHtml(b,k):a.bindingHandlers.text.update(b,function(){return k}),m&&!l?b.style.display="none":!m&&l&&(b.style.display="")}},a.bindingHandlers.validationElement={update:function(b,c,d){var e=c(),g=f.utils.getConfigOptions(b),i=(h(e),!1),j=!1;if(null===e||"undefined"==typeof e)throw new Error("Cannot bind validationElement to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!e.isValid||!e.isModified)throw new Error("Observable is not validatable");i=e.isModified(),j=e.isValid();var k=function(){var a={},b=!g.decorateElementOnModified||i?!j:!1;return a[g.errorElementClass]=b,a};a.bindingHandlers.css.update(b,k,d),g.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!g.errorsAsTitleOnModified||i,c=f.utils.getOriginalElementTitle(b);return a&&!j?{title:e.error,"data-orig-title":c}:!a||j?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){b.error(a),b.__valid__(!1)},b.clearError=function(){return b.error(null),b.__valid__(!0),b};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){b(),b.rules();return f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified.getSubscriptionsCount()>0&&(b.isModified._subscriptions.change=[]),b.isValidating.getSubscriptionsCount()>0&&(b.isValidating._subscriptions.change=[]),b.__valid__.getSubscriptionsCount()>0&&(b.__valid__._subscriptions.change=[]),g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=c.rule?f.rules[c.rule]:c,b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0},f.localize=function(a){var b;for(b in a)f.rules.hasOwnProperty(b)&&(f.rules[b].message=a[b])},a.applyBindingsWithValidation=function(b,c,d){var e,g=document.body;c&&c.nodeType?(g=c,e=d):e=c,f.init(),e&&(e=j(j({},f.configuration),e),f.utils.setDomData(g,e)),a.applyBindings(b,g)};var n=a.applyBindings;a.applyBindings=function(a,b){f.init(),n(a,b)},a.validatedObservable=function(b,c){if(!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var d=a.observable(b);return d.errors=f.group(b,c),d.isValid=a.observable(0===d.errors().length),a.isObservable(d.errors)?d.errors.subscribe(function(a){d.isValid(0===a.length)}):a.computed(d.errors).subscribe(function(a){d.isValid(0===a.length)}),d}}); //# sourceMappingURL=knockout.validation.min.js.map \ No newline at end of file diff --git a/Dist/knockout.validation.min.js.map b/Dist/knockout.validation.min.js.map index 6a9af96f..1b225f42 100644 --- a/Dist/knockout.validation.min.js.map +++ b/Dist/knockout.validation.min.js.map @@ -1 +1 @@ -{"version":3,"file":"knockout.validation.min.js","sources":["knockout.validation.js"],"names":["factory","require","exports","module","define","ko","validation","minMaxValidatorFactory","validatorName","isMaxValidation","val","options","kv","utils","isEmptyVal","comparisonValue","type","undefined","typeAttr","value","isNaN","Date","regex","valMatches","comparisonValueMatches","toLowerCase","match","parseFloat","validateSync","observable","rule","ctx","validator","params","unwrap","setError","formatMessage","message","validateAsync","isValidating","callBack","valObj","isValid","msg","__valid__","error","koUtils","unwrapObservable","forEach","arrayForEach","extend","defaults","registerExtenders","messagesOnModified","errorsAsTitle","errorsAsTitleOnModified","messageTemplate","insertMessages","parseInputAttributes","writeInputAttributes","decorateInputElement","decorateElementOnModified","errorClass","errorElementClass","errorMessageClass","allowHtmlMessages","grouping","deep","live","validate","configuration","html5Attributes","html5InputTypes","reset","seedId","getTime","domData","domDataKey","isArray","o","Object","prototype","toString","call","isObject","isNumber","isObservableArray","instance","values","r","i","hasOwnProperty","push","getValue","hasAttribute","node","attr","getAttribute","element","setAttribute","isValidatable","rules","isModified","insertAfter","newNode","parentNode","insertBefore","nextSibling","newId","getConfigOptions","contextFor","setDomData","data","key","getDomData","nodeType","context","getOriginalElementTitle","savedOriginalTitle","currentTitle","title","hasSavedOriginalTitle","async","expr","window","setImmediate","setTimeout","object","callback","prop","api","cleanUpSubscriptions","subscriptions","subscription","dispose","flagged","obj","__kv_traversed","length","runTraversal","validatables","traverseGraph","level","objValues","peek","isObservable","validatable","subscribe","graphMonitor","valueHasMutated","_destroy","collectErrors","array","errors","isInitialized","init","force","configure","group","result","computed","showAllMessages","show","isAnyMessageShown","invalidAndModifiedPresent","arrayFirst","replacements","replace","index","addRule","addAnonymousRule","ruleObj","onlyIf","condition","addExtender","ruleName","extenders","insertValidationMessage","span","document","createElement","className","parseInputValidationAttributes","valueAccessor","currentType","writeInputValidationAttributes","contexts","read","RegExp","source","disposeWhenNodeIsRemoved","makeBindingHandlerValidatable","handlerName","bindingHandlers","allBindingsAccessor","viewModel","bindingContext","setRules","target","definition","ruleDefinitions","targetValue","unwrappedTargetValue","nonRules","required","testVal","String","trim","minLength","normalizedVal","maxLength","step","dif","Math","abs","test","phoneNumber","otherValue","c","collection","external","externalValue","counter","arrayFilter","item","config","validationMessageElement","renderTemplate","field","applyBindingsToNode","validationMessage","validationElement","textInput","update","obsv","Error","isVisible","isCurrentlyVisible","style","display","setHtml","text","cssSettingsAccessor","css","shouldShow","hasModification","data-orig-title","newConfig","enable","validationOptions","throttleEvaluation","throttle","observableArray","clearError","h_change","h_obsValidationTrigger","validateObservable","_disposeValidation","removeAll","getSubscriptionsCount","_subscriptions","ruleContexts","len","localize","msgTranslations","applyBindingsWithValidation","rootNode","body","applyBindings","origApplyBindings","validatedObservable","initialValue"],"mappings":";;;;;;;;;CAUC,SAAUA,GAGgB,kBAAZC,UAA6C,gBAAZC,UAA0C,gBAAXC,QAEvEH,EAAQC,QAAQ,YAAaC,SACJ,kBAAXE,SAAyBA,OAAY,IAEnDA,QAAQ,WAAY,WAAYJ,GAGhCA,EAAQK,GAAIA,GAAGC,gBAErB,SAAWD,EAAIH,GAmqBjB,QAASK,GAAuBC,GAC5B,GAAIC,GAAoC,QAAlBD,CAEtB,OAAO,UAAUE,EAAKC,GAClB,GAAIC,EAAGC,MAAMC,WAAWJ,GACpB,OAAO,CAGX,IAAIK,GAAiBC,CACIC,UA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,QACxBiF,EAAKjF,OAAON,UAAU,SAAUM,GAC9BiF,EAAKhM,QAA0B,IAAlB+G,EAAOf,UAIrBrI,EAAG2J,SAAS0E,EAAKjF,QAAQN,UAAU,SAAUM,GAC5CiF,EAAKhM,QAA0B,IAAlB+G,EAAOf,UAIhBgG"} \ No newline at end of file +{"version":3,"file":"knockout.validation.min.js","sources":["knockout.validation.js"],"names":["factory","require","exports","module","define","ko","validation","minMaxValidatorFactory","validatorName","isMaxValidation","val","options","kv","utils","isEmptyVal","comparisonValue","type","undefined","typeAttr","value","isNaN","Date","regex","valMatches","comparisonValueMatches","toLowerCase","match","parseFloat","validateSync","observable","rule","ctx","validator","params","unwrap","setError","formatMessage","message","validateAsync","isValidating","callBack","valObj","isValid","msg","__valid__","error","koUtils","unwrapObservable","forEach","arrayForEach","extend","defaults","registerExtenders","messagesOnModified","errorsAsTitle","errorsAsTitleOnModified","messageTemplate","insertMessages","parseInputAttributes","writeInputAttributes","decorateInputElement","decorateElementOnModified","errorClass","errorElementClass","errorMessageClass","allowHtmlMessages","grouping","deep","live","validate","configuration","html5Attributes","html5InputTypes","reset","seedId","getTime","domData","domDataKey","isArray","o","Object","prototype","toString","call","isObject","isNumber","isObservableArray","instance","values","r","i","hasOwnProperty","push","getValue","hasAttribute","node","attr","getAttribute","element","setAttribute","isValidatable","rules","isModified","insertAfter","newNode","parentNode","insertBefore","nextSibling","newId","getConfigOptions","contextFor","setDomData","data","key","getDomData","nodeType","context","getOriginalElementTitle","savedOriginalTitle","currentTitle","title","hasSavedOriginalTitle","async","expr","window","setImmediate","setTimeout","object","callback","prop","api","cleanUpSubscriptions","subscriptions","subscription","dispose","flagged","obj","__kv_traversed","length","runTraversal","validatables","traverseGraph","level","objValues","peek","isObservable","validatable","subscribe","graphMonitor","valueHasMutated","_destroy","collectErrors","array","errors","isInitialized","init","force","configure","group","result","computed","showAllMessages","show","isAnyMessageShown","invalidAndModifiedPresent","arrayFirst","replacements","replace","index","addRule","addAnonymousRule","ruleObj","onlyIf","condition","addExtender","ruleName","extenders","insertValidationMessage","span","document","createElement","className","parseInputValidationAttributes","valueAccessor","currentType","writeInputValidationAttributes","contexts","read","RegExp","source","disposeWhenNodeIsRemoved","makeBindingHandlerValidatable","handlerName","bindingHandlers","allBindingsAccessor","viewModel","bindingContext","setRules","target","definition","ruleDefinitions","targetValue","unwrappedTargetValue","nonRules","required","testVal","String","trim","minLength","normalizedVal","maxLength","step","dif","Math","abs","test","phoneNumber","otherValue","c","collection","external","externalValue","counter","arrayFilter","item","config","validationMessageElement","renderTemplate","field","applyBindingsToNode","validationMessage","validationElement","textInput","update","obsv","Error","isVisible","isCurrentlyVisible","style","display","setHtml","text","cssSettingsAccessor","css","shouldShow","hasModification","data-orig-title","newConfig","enable","validationOptions","throttleEvaluation","throttle","observableArray","clearError","h_change","h_obsValidationTrigger","validateObservable","_disposeValidation","removeAll","getSubscriptionsCount","_subscriptions","ruleContexts","len","localize","msgTranslations","applyBindingsWithValidation","rootNode","body","applyBindings","origApplyBindings","validatedObservable","initialValue"],"mappings":";;;;;;;;;CAUC,SAAUA,GAGgB,kBAAZC,UAA6C,gBAAZC,UAA0C,gBAAXC,QAEvEH,EAAQC,QAAQ,YAAaC,SACJ,kBAAXE,SAAyBA,OAAY,IAEnDA,QAAQ,WAAY,WAAYJ,GAGhCA,EAAQK,GAAIA,GAAGC,gBAErB,SAAWD,EAAIH,GAmqBjB,QAASK,GAAuBC,GAC5B,GAAIC,GAAoC,QAAlBD,CAEtB,OAAO,UAAUE,EAAKC,GAClB,GAAIC,EAAGC,MAAMC,WAAWJ,GACpB,OAAO,CAGX,IAAIK,GAAiBC,CACIC,UAArBN,EAAQO,UAGRF,EAAO,OACPD,EAAkBJ,IAElBK,EAAOL,EAAQO,SACfH,EAAkBJ,EAAQQ,OAKzBC,MAAML,IAAsBA,YAA2BM,QACxDL,EAAO,SAGX,IAAIM,GAAOC,EAAYC,CACvB,QAAQR,EAAKS,eACT,IAAK,OAGD,GAFAH,EAA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bb6fd8e0bb0a5adeed2dc10fee446e7d9 Mon Sep 17 00:00:00 2001 From: crissdev Date: Wed, 24 Dec 2014 13:43:54 +0200 Subject: [PATCH 114/165] Fix #99 - Prevent ko.validation.group to notify with intermediary validation state --- Dist/knockout.validation.js | 42 +++++++++++++++++------------ Dist/knockout.validation.min.js | 2 +- Dist/knockout.validation.min.js.map | 2 +- Src/api.js | 42 +++++++++++++++++------------ Tests/api-tests.js | 20 ++++++++++++++ 5 files changed, 72 insertions(+), 36 deletions(-) diff --git a/Dist/knockout.validation.js b/Dist/knockout.validation.js index b096a81d..462cfbb6 100644 --- a/Dist/knockout.validation.js +++ b/Dist/knockout.validation.js @@ -225,16 +225,18 @@ kv.configuration = configuration; cleanUpSubscriptions(context); traverseGraph(obj, context); dispose(context); - } + } function traverseGraph(obj, context, level) { var objValues = [], val = obj.peek ? obj.peek() : obj; - if (obj.__kv_traversed === true) { return; } + if (obj.__kv_traversed === true) { + return; + } if (context.options.deep) { - obj.__kv_traversed = true; + obj.__kv_traversed = true; context.flagged.push(obj); } @@ -245,27 +247,30 @@ kv.configuration = configuration; if (ko.isObservable(obj)) { //make sure it is validatable object - if (!obj.isValid) { obj.extend({ validatable: true }); } + if (!obj.isValid) { + obj.extend({ validatable: true }); + } context.validatables.push(obj); - if(context.options.live && utils.isObservableArray(obj)) { + if (context.options.live && utils.isObservableArray(obj)) { context.subscriptions.push(obj.subscribe(function () { context.graphMonitor.valueHasMutated(); })); - } + } } //get list of values either from array or object but ignore non-objects // and destroyed objects if (val && !val._destroy) { if (utils.isArray(val)) { - objValues = val; - } else if (utils.isObject(val)) { + objValues = val; + } + else if (utils.isObject(val)) { objValues = utils.values(val); - } + } } - //process recurisvely if it is deep grouping + //process recursively if it is deep grouping if (level !== 0) { utils.forEach(objValues, function (observable) { @@ -281,7 +286,9 @@ kv.configuration = configuration; var errors = []; forEach(array, function (observable) { if (!observable.isValid()) { - errors.push(observable.error()); + // Use peek because we don't want a dependency for 'error' property because it + // changes before 'isValid' does. (Issue #99) + errors.push(observable.error.peek()); } }); return errors; @@ -312,13 +319,13 @@ kv.configuration = configuration; isInitialized = 1; }, - // backwards compatability + // backwards compatibility configure: function (options) { kv.init(options); }, // resets the config back to its original state reset: kv.configuration.reset, - // recursivly walks a viewModel and creates an object that + // recursively walks a viewModel and creates an object that // provides validation information for the entire viewModel // obj -> the viewModel to walk // options -> { @@ -334,7 +341,7 @@ kv.configuration = configuration; flagged: [], subscriptions: [], validatables: [] - }; + }; var result = null; @@ -349,7 +356,8 @@ kv.configuration = configuration; return collectErrors(context.validatables); }); - } else { //if not using observables then every call to error() should traverse the structure + } + else { //if not using observables then every call to error() should traverse the structure result = function () { runTraversal(obj, context); @@ -573,10 +581,10 @@ kv.configuration = configuration; // we have to do some special things for the pattern validation if (ctx.rule === "pattern" && params instanceof RegExp) { // we need the pure string representation of the RegExpr without the //gi stuff - params = params.source; + params = params.source; } - element.setAttribute(attr, params); + element.setAttribute(attr, params); }, disposeWhenNodeIsRemoved: element }); diff --git a/Dist/knockout.validation.min.js b/Dist/knockout.validation.min.js index 5272033e..a0750345 100644 --- a/Dist/knockout.validation.min.js +++ b/Dist/knockout.validation.min.js @@ -7,5 +7,5 @@ =============================================================================== */ -!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||e instanceof Date||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for week input. Should look like '2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for month input. Should look like '2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:h(c.params))?!0:(a.setError(f.formatMessage(c.message||b.message,h(c.params),a)),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,h(c.params),a)),a.__valid__(e)),void a.isValidating(!1)):void a.isValidating(!1)};b.validator(a(),h(c.params||!0),d)}if("undefined"==typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0,live:!1},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},isNumber:function(a){return!isNaN(a)},isObservableArray:function(a){return!!a&&"function"==typeof a.remove&&"function"==typeof a.removeAll&&"function"==typeof a.destroy&&"function"==typeof a.destroyAll&&"function"==typeof a.indexOf&&"function"==typeof a.replace},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return!!(a&&a.rules&&a.isValid&&a.isModified)},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},forEach:function(a,b){if(f.utils.isArray(a))return i(a,b);for(var c in a)a.hasOwnProperty(c)&&b(a[c],c)}}}();var m=function(){function b(a){i(a.subscriptions,function(a){a.dispose()}),a.subscriptions=[]}function c(a){a.options.deep&&(i(a.flagged,function(a){delete a.__kv_traversed}),a.flagged.length=0),a.options.live||b(a)}function d(a,d){d.validatables=[],b(d),e(a,d),c(d)}function e(b,c,d){var f=[],g=b.peek?b.peek():b;b.__kv_traversed!==!0&&(c.options.deep&&(b.__kv_traversed=!0,c.flagged.push(b)),d=void 0!==d?d:c.options.deep?1:-1,a.isObservable(b)&&(b.isValid||b.extend({validatable:!0}),c.validatables.push(b),c.options.live&&n.isObservableArray(b)&&c.subscriptions.push(b.subscribe(function(){c.graphMonitor.valueHasMutated()}))),g&&!g._destroy&&(n.isArray(g)?f=g:n.isObject(g)&&(f=n.values(g))),0!==d&&n.forEach(f,function(a){a&&!a.nodeType&&e(a,c,d+1)}))}function k(a){var b=[];return i(a,function(a){a.isValid()||b.push(a.error())}),b}var l=0,m=f.configuration,n=f.utils;return{init:function(a,b){l>0&&!b||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||m.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||m.errorMessageClass,j(m,a),m.registerExtenders&&f.registerExtenders(),l=1)},configure:function(a){f.init(a)},reset:f.configuration.reset,group:function(b,c){c=j(j({},m.grouping),c);var e={options:c,graphMonitor:a.observable(),flagged:[],subscriptions:[],validatables:[]},f=null;return c.observable?(d(b,e),f=a.computed(function(){return e.graphMonitor(),d(b,e),k(e.validatables)})):f=function(){return d(b,e),k(e.validatables)},f.showAllMessages=function(a){void 0===a&&(a=!0),f(),i(e.validatables,function(b){b.isModified(a)})},f.isAnyMessageShown=function(){var a=!1;return f(),a=!!g.arrayFirst(e.validatables,function(a){return!a.isValid()&&a.isModified()})},f},formatMessage:function(a,b,c){if(n.isObject(b)&&b.typeAttr&&(b=b.value),"function"==typeof a)return a(b,c);var d=h(b)||[];return n.isArray(d)||(d=[d]),a.replace(/{(\d+)}/gi,function(a,b){return"undefined"!=typeof d[b]?d[b]:a})},addRule:function(a,b){return a.extend({validatable:!0}),a.rules.push(b),a},addAnonymousRule:function(a,b){void 0===b.message&&(b.message="Error"),b.onlyIf&&(b.condition=b.onlyIf),f.addRule(a,b)},addExtender:function(b){a.extenders[b]=function(a,c){return c&&(c.message||c.onlyIf)?f.addRule(a,{rule:b,message:c.message,params:n.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(m.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=n.getConfigOptions(a).errorMessageClass,n.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(n.hasAttribute(a,c)){var d=a.getAttribute(c)||!0;if("min"===c||"max"===c){var e=a.getAttribute("type");"undefined"!=typeof e&&e||(e="text"),d={typeAttr:e,value:d}}f.addRule(b(),{rule:c,params:d})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(b,c){var d=c();if(d&&d.rules){var e=d.rules();i(f.configuration.html5Attributes,function(c){var d=g.arrayFirst(e,function(a){return a.rule&&a.rule.toLowerCase()===c.toLowerCase()});d&&a.computed({read:function(){var e=a.unwrap(d.params);"pattern"===d.rule&&e instanceof RegExp&&(e=e.source),b.setAttribute(c,e)},disposeWhenNodeIsRemoved:b})}),e=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var d=function(b,c){if(b&&c)for(var e in c)if(c.hasOwnProperty(e)){var g=c[e];if(b[e]){var i=b[e],j=h(i),k={},l={};for(var m in g)g.hasOwnProperty(m)&&(f.rules[m]?k[m]=g[m]:l[m]=g[m]);if(a.isObservable(i)&&i.extend(k),j&&n.isArray(j))for(var o=0;o0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}."},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address."},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date."},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[-/](?:0?[1-9]|1[012])[-/](?:0?[1-9]|[12][0-9]|3[01])$/.test(a):!0},message:"Please enter a proper date."},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number."},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit."},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number."},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal."},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(c,function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateInputElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.textInput&&f.makeBindingHandlerValidatable("textInput"),f.makeBindingHandlerValidatable("selectedOptions"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),i=(h(d),!1),j=!1;if(null===d||"undefined"==typeof d)throw new Error("Cannot bind validationMessage to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");i=d.isModified(),j=d.isValid();var k=null;(!e.messagesOnModified||i)&&(k=j?null:d.error);var l=!e.messagesOnModified||i?!j:!1,m="none"!==b.style.display;e.allowHtmlMessages?g.setHtml(b,k):a.bindingHandlers.text.update(b,function(){return k}),m&&!l?b.style.display="none":!m&&l&&(b.style.display="")}},a.bindingHandlers.validationElement={update:function(b,c,d){var e=c(),g=f.utils.getConfigOptions(b),i=(h(e),!1),j=!1;if(null===e||"undefined"==typeof e)throw new Error("Cannot bind validationElement to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!e.isValid||!e.isModified)throw new Error("Observable is not validatable");i=e.isModified(),j=e.isValid();var k=function(){var a={},b=!g.decorateElementOnModified||i?!j:!1;return a[g.errorElementClass]=b,a};a.bindingHandlers.css.update(b,k,d),g.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!g.errorsAsTitleOnModified||i,c=f.utils.getOriginalElementTitle(b);return a&&!j?{title:e.error,"data-orig-title":c}:!a||j?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){b.error(a),b.__valid__(!1)},b.clearError=function(){return b.error(null),b.__valid__(!0),b};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){b(),b.rules();return f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified.getSubscriptionsCount()>0&&(b.isModified._subscriptions.change=[]),b.isValidating.getSubscriptionsCount()>0&&(b.isValidating._subscriptions.change=[]),b.__valid__.getSubscriptionsCount()>0&&(b.__valid__._subscriptions.change=[]),g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=c.rule?f.rules[c.rule]:c,b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0},f.localize=function(a){var b;for(b in a)f.rules.hasOwnProperty(b)&&(f.rules[b].message=a[b])},a.applyBindingsWithValidation=function(b,c,d){var e,g=document.body;c&&c.nodeType?(g=c,e=d):e=c,f.init(),e&&(e=j(j({},f.configuration),e),f.utils.setDomData(g,e)),a.applyBindings(b,g)};var n=a.applyBindings;a.applyBindings=function(a,b){f.init(),n(a,b)},a.validatedObservable=function(b,c){if(!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var d=a.observable(b);return d.errors=f.group(b,c),d.isValid=a.observable(0===d.errors().length),a.isObservable(d.errors)?d.errors.subscribe(function(a){d.isValid(0===a.length)}):a.computed(d.errors).subscribe(function(a){d.isValid(0===a.length)}),d}}); +!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||e instanceof Date||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for week input. Should look like '2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for month input. Should look like '2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:h(c.params))?!0:(a.setError(f.formatMessage(c.message||b.message,h(c.params),a)),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,h(c.params),a)),a.__valid__(e)),void a.isValidating(!1)):void a.isValidating(!1)};b.validator(a(),h(c.params||!0),d)}if("undefined"==typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0,live:!1},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},isNumber:function(a){return!isNaN(a)},isObservableArray:function(a){return!!a&&"function"==typeof a.remove&&"function"==typeof a.removeAll&&"function"==typeof a.destroy&&"function"==typeof a.destroyAll&&"function"==typeof a.indexOf&&"function"==typeof a.replace},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return!!(a&&a.rules&&a.isValid&&a.isModified)},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},forEach:function(a,b){if(f.utils.isArray(a))return i(a,b);for(var c in a)a.hasOwnProperty(c)&&b(a[c],c)}}}();var m=function(){function b(a){i(a.subscriptions,function(a){a.dispose()}),a.subscriptions=[]}function c(a){a.options.deep&&(i(a.flagged,function(a){delete a.__kv_traversed}),a.flagged.length=0),a.options.live||b(a)}function d(a,d){d.validatables=[],b(d),e(a,d),c(d)}function e(b,c,d){var f=[],g=b.peek?b.peek():b;b.__kv_traversed!==!0&&(c.options.deep&&(b.__kv_traversed=!0,c.flagged.push(b)),d=void 0!==d?d:c.options.deep?1:-1,a.isObservable(b)&&(b.isValid||b.extend({validatable:!0}),c.validatables.push(b),c.options.live&&n.isObservableArray(b)&&c.subscriptions.push(b.subscribe(function(){c.graphMonitor.valueHasMutated()}))),g&&!g._destroy&&(n.isArray(g)?f=g:n.isObject(g)&&(f=n.values(g))),0!==d&&n.forEach(f,function(a){a&&!a.nodeType&&e(a,c,d+1)}))}function k(a){var b=[];return i(a,function(a){a.isValid()||b.push(a.error.peek())}),b}var l=0,m=f.configuration,n=f.utils;return{init:function(a,b){l>0&&!b||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||m.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||m.errorMessageClass,j(m,a),m.registerExtenders&&f.registerExtenders(),l=1)},configure:function(a){f.init(a)},reset:f.configuration.reset,group:function(b,c){c=j(j({},m.grouping),c);var e={options:c,graphMonitor:a.observable(),flagged:[],subscriptions:[],validatables:[]},f=null;return c.observable?(d(b,e),f=a.computed(function(){return e.graphMonitor(),d(b,e),k(e.validatables)})):f=function(){return d(b,e),k(e.validatables)},f.showAllMessages=function(a){void 0===a&&(a=!0),f(),i(e.validatables,function(b){b.isModified(a)})},f.isAnyMessageShown=function(){var a=!1;return f(),a=!!g.arrayFirst(e.validatables,function(a){return!a.isValid()&&a.isModified()})},f},formatMessage:function(a,b,c){if(n.isObject(b)&&b.typeAttr&&(b=b.value),"function"==typeof a)return a(b,c);var d=h(b)||[];return n.isArray(d)||(d=[d]),a.replace(/{(\d+)}/gi,function(a,b){return"undefined"!=typeof d[b]?d[b]:a})},addRule:function(a,b){return a.extend({validatable:!0}),a.rules.push(b),a},addAnonymousRule:function(a,b){void 0===b.message&&(b.message="Error"),b.onlyIf&&(b.condition=b.onlyIf),f.addRule(a,b)},addExtender:function(b){a.extenders[b]=function(a,c){return c&&(c.message||c.onlyIf)?f.addRule(a,{rule:b,message:c.message,params:n.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(m.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=n.getConfigOptions(a).errorMessageClass,n.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(n.hasAttribute(a,c)){var d=a.getAttribute(c)||!0;if("min"===c||"max"===c){var e=a.getAttribute("type");"undefined"!=typeof e&&e||(e="text"),d={typeAttr:e,value:d}}f.addRule(b(),{rule:c,params:d})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(b,c){var d=c();if(d&&d.rules){var e=d.rules();i(f.configuration.html5Attributes,function(c){var d=g.arrayFirst(e,function(a){return a.rule&&a.rule.toLowerCase()===c.toLowerCase()});d&&a.computed({read:function(){var e=a.unwrap(d.params);"pattern"===d.rule&&e instanceof RegExp&&(e=e.source),b.setAttribute(c,e)},disposeWhenNodeIsRemoved:b})}),e=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var d=function(b,c){if(b&&c)for(var e in c)if(c.hasOwnProperty(e)){var g=c[e];if(b[e]){var i=b[e],j=h(i),k={},l={};for(var m in g)g.hasOwnProperty(m)&&(f.rules[m]?k[m]=g[m]:l[m]=g[m]);if(a.isObservable(i)&&i.extend(k),j&&n.isArray(j))for(var o=0;o0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}."},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address."},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date."},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[-/](?:0?[1-9]|1[012])[-/](?:0?[1-9]|[12][0-9]|3[01])$/.test(a):!0},message:"Please enter a proper date."},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number."},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit."},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number."},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal."},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(c,function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateInputElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.textInput&&f.makeBindingHandlerValidatable("textInput"),f.makeBindingHandlerValidatable("selectedOptions"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),i=(h(d),!1),j=!1;if(null===d||"undefined"==typeof d)throw new Error("Cannot bind validationMessage to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");i=d.isModified(),j=d.isValid();var k=null;(!e.messagesOnModified||i)&&(k=j?null:d.error);var l=!e.messagesOnModified||i?!j:!1,m="none"!==b.style.display;e.allowHtmlMessages?g.setHtml(b,k):a.bindingHandlers.text.update(b,function(){return k}),m&&!l?b.style.display="none":!m&&l&&(b.style.display="")}},a.bindingHandlers.validationElement={update:function(b,c,d){var e=c(),g=f.utils.getConfigOptions(b),i=(h(e),!1),j=!1;if(null===e||"undefined"==typeof e)throw new Error("Cannot bind validationElement to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!e.isValid||!e.isModified)throw new Error("Observable is not validatable");i=e.isModified(),j=e.isValid();var k=function(){var a={},b=!g.decorateElementOnModified||i?!j:!1;return a[g.errorElementClass]=b,a};a.bindingHandlers.css.update(b,k,d),g.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!g.errorsAsTitleOnModified||i,c=f.utils.getOriginalElementTitle(b);return a&&!j?{title:e.error,"data-orig-title":c}:!a||j?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){b.error(a),b.__valid__(!1)},b.clearError=function(){return b.error(null),b.__valid__(!0),b};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){b(),b.rules();return f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified.getSubscriptionsCount()>0&&(b.isModified._subscriptions.change=[]),b.isValidating.getSubscriptionsCount()>0&&(b.isValidating._subscriptions.change=[]),b.__valid__.getSubscriptionsCount()>0&&(b.__valid__._subscriptions.change=[]),g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=c.rule?f.rules[c.rule]:c,b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0},f.localize=function(a){var b;for(b in a)f.rules.hasOwnProperty(b)&&(f.rules[b].message=a[b])},a.applyBindingsWithValidation=function(b,c,d){var e,g=document.body;c&&c.nodeType?(g=c,e=d):e=c,f.init(),e&&(e=j(j({},f.configuration),e),f.utils.setDomData(g,e)),a.applyBindings(b,g)};var n=a.applyBindings;a.applyBindings=function(a,b){f.init(),n(a,b)},a.validatedObservable=function(b,c){if(!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var d=a.observable(b);return d.errors=f.group(b,c),d.isValid=a.observable(0===d.errors().length),a.isObservable(d.errors)?d.errors.subscribe(function(a){d.isValid(0===a.length)}):a.computed(d.errors).subscribe(function(a){d.isValid(0===a.length)}),d}}); //# sourceMappingURL=knockout.validation.min.js.map \ No newline at end of file diff --git a/Dist/knockout.validation.min.js.map b/Dist/knockout.validation.min.js.map index 1b225f42..62d753ad 100644 --- a/Dist/knockout.validation.min.js.map +++ b/Dist/knockout.validation.min.js.map @@ -1 +1 @@ -{"version":3,"file":"knockout.validation.min.js","sources":["knockout.validation.js"],"names":["factory","require","exports","module","define","ko","validation","minMaxValidatorFactory","validatorName","isMaxValidation","val","options","kv","utils","isEmptyVal","comparisonValue","type","undefined","typeAttr","value","isNaN","Date","regex","valMatches","comparisonValueMatches","toLowerCase","match","parseFloat","validateSync","observable","rule","ctx","validator","params","unwrap","setError","formatMessage","message","validateAsync","isValidating","callBack","valObj","isValid","msg","__valid__","error","koUtils","unwrapObservable","forEach","arrayForEach","extend","defaults","registerExtenders","messagesOnModified","errorsAsTitle","errorsAsTitleOnModified","messageTemplate","insertMessages","parseInputAttributes","writeInputAttributes","decorateInputElement","decorateElementOnModified","errorClass","errorElementClass","errorMessageClass","allowHtmlMessages","grouping","deep","live","validate","configuration","html5Attributes","html5InputTypes","reset","seedId","getTime","domData","domDataKey","isArray","o","Object","prototype","toString","call","isObject","isNumber","isObservableArray","instance","values","r","i","hasOwnProperty","push","getValue","hasAttribute","node","attr","getAttribute","element","setAttribute","isValidatable","rules","isModified","insertAfter","newNode","parentNode","insertBefore","nextSibling","newId","getConfigOptions","contextFor","setDomData","data","key","getDomData","nodeType","context","getOriginalElementTitle","savedOriginalTitle","currentTitle","title","hasSavedOriginalTitle","async","expr","window","setImmediate","setTimeout","object","callback","prop","api","cleanUpSubscriptions","subscriptions","subscription","dispose","flagged","obj","__kv_traversed","length","runTraversal","validatables","traverseGraph","level","objValues","peek","isObservable","validatable","subscribe","graphMonitor","valueHasMutated","_destroy","collectErrors","array","errors","isInitialized","init","force","configure","group","result","computed","showAllMessages","show","isAnyMessageShown","invalidAndModifiedPresent","arrayFirst","replacements","replace","index","addRule","addAnonymousRule","ruleObj","onlyIf","condition","addExtender","ruleName","extenders","insertValidationMessage","span","document","createElement","className","parseInputValidationAttributes","valueAccessor","currentType","writeInputValidationAttributes","contexts","read","RegExp","source","disposeWhenNodeIsRemoved","makeBindingHandlerValidatable","handlerName","bindingHandlers","allBindingsAccessor","viewModel","bindingContext","setRules","target","definition","ruleDefinitions","targetValue","unwrappedTargetValue","nonRules","required","testVal","String","trim","minLength","normalizedVal","maxLength","step","dif","Math","abs","test","phoneNumber","otherValue","c","collection","external","externalValue","counter","arrayFilter","item","config","validationMessageElement","renderTemplate","field","applyBindingsToNode","validationMessage","validationElement","textInput","update","obsv","Error","isVisible","isCurrentlyVisible","style","display","setHtml","text","cssSettingsAccessor","css","shouldShow","hasModification","data-orig-title","newConfig","enable","validationOptions","throttleEvaluation","throttle","observableArray","clearError","h_change","h_obsValidationTrigger","validateObservable","_disposeValidation","removeAll","getSubscriptionsCount","_subscriptions","ruleContexts","len","localize","msgTranslations","applyBindingsWithValidation","rootNode","body","applyBindings","origApplyBindings","validatedObservable","initialValue"],"mappings":";;;;;;;;;CAUC,SAAUA,GAGgB,kBAAZC,UAA6C,gBAAZC,UAA0C,gBAAXC,QAEvEH,EAAQC,QAAQ,YAAaC,SACJ,kBAAXE,SAAyBA,OAAY,IAEnDA,QAAQ,WAAY,WAAYJ,GAGhCA,EAAQK,GAAIA,GAAGC,gBAErB,SAAWD,EAAIH,GAmqBjB,QAASK,GAAuBC,GAC5B,GAAIC,GAAoC,QAAlBD,CAEtB,OAAO,UAAUE,EAAKC,GAClB,GAAIC,EAAGC,MAAMC,WAAWJ,GACpB,OAAO,CAGX,IAAIK,GAAiBC,CACIC,UAArBN,EAAQO,UAGRF,EAAO,O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AAU,SAAUM,GAC9BiF,EAAKhM,QAA0B,IAAlB+G,EAAOf,UAIrBrI,EAAG2J,SAAS0E,EAAKjF,QAAQN,UAAU,SAAUM,GAC5CiF,EAAKhM,QAA0B,IAAlB+G,EAAOf,UAIhBgG"} \ No newline at end of file +{"version":3,"file":"knockout.validation.min.js","sources":["knockout.validation.js"],"names":["factory","require","exports","module","define","ko","validation","minMaxValidatorFactory","validatorName","isMaxValidation","val","options","kv","utils","isEmptyVal","comparisonValue","type","undefined","typeAttr","value","isNaN","Date","regex","valMatches","comparisonValueMatches","toLowerCase","match","parseFloat","validateSync","observable","rule","ctx","validator","params","unwrap","setError","formatMessage","message","validateAsync","isValidating","callBack","valObj","isValid","msg","__valid__","error","koUtils","unwrapObservable","forEach","arrayForEach","extend","defaults","registerExtenders","messagesOnModified","errorsAsTitle","errorsAsTitleOnModified","messageTemplate","insertMessages","parseInputAttributes","writeInputAttributes","decorateInputElement","decorateElementOnModified","errorClass","errorElementClass","errorMessageClass","allowHtmlMessages","grouping","deep","live","validate","configuration","html5Attributes","html5InputTypes","reset","seedId","getTime","domData","domDataKey","isArray","o","Object","prototype","toString","call","isObject","isNumber","isObservableArray","instance","values","r","i","hasOwnProperty","push","getValue","hasAttribute","node","attr","getAttribute","element","setAttribute","isValidatable","rules","isModified","insertAfter","newNode","parentNode","insertBefore","nextSibling","newId","getConfigOptions","contextFor","setDomData","data","key","getDomData","nodeType","context","getOriginalElementTitle","savedOriginalTitle","currentTitle","title","hasSavedOriginalTitle","async","expr","window","setImmediate","setTimeout","object","callback","prop","api","cleanUpSubscriptions","subscriptions","subscription","dispose","flagged","obj","__kv_traversed","length","runTraversal","validatables","traverseGraph","level","objValues","peek","isObservable","validatable","subscribe","graphMonitor","valueHasMutated","_destroy","collectErrors","array","errors","isInitialized","init","force","configure","group","result","computed","showAllMessages","show","isAnyMessageShown","invalidAndModifiedPresent","arrayFirst","replacements","replace","index","addRule","addAnonymousRule","ruleObj","onlyIf","condition","addExtender","ruleName","extenders","insertValidationMessage","span","document","createElement","className","parseInputValidationAttributes","valueAccessor","currentType","writeInputValidationAttributes","contexts","read","RegExp","source","disposeWhenNodeIsRemoved","makeBindingHandlerValidatable","handlerName","bindingHandlers","allBindingsAccessor","viewModel","bindingContext","setRules","target","definition","ruleDefinitions","targetValue","unwrappedTargetValue","nonRules","required","testVal","String","trim","minLength","normalizedVal","maxLength","step","dif","Math","abs","test","phoneNumber","otherValue","c","collection","external","externalValue","counter","arrayFilter","item","config","validationMessageElement","renderTemplate","field","applyBindingsToNode","validationMessage","validationElement","textInput","update","obsv","Error","isVisible","isCurrentlyVisible","style","display","setHtml","text","cssSettingsAccessor","css","shouldShow","hasModification","data-orig-title","newConfig","enable","validationOptions","throttleEvaluation","throttle","observableArray","clearError","h_change","h_obsValidationTrigger","validateObservable","_disposeValidation","removeAll","getSubscriptionsCount","_subscriptions","ruleContexts","len","localize","msgTranslations","applyBindingsWithValidation","rootNode","body","applyBindings","origApplyBindings","validatedObservable","initialValue"],"mappings":";;;;;;;;;CAUC,SAAUA,GAGgB,kBAAZC,UAA6C,gBAAZC,UAA0C,gBAAXC,QAEvEH,EAAQC,QAAQ,YAAaC,SACJ,kBAAXE,SAAyBA,OAAY,IAEnDA,QAAQ,WAAY,WAAYJ,GAGhCA,EAAQK,GAAIA,GAAGC,gBAErB,SAAWD,EAAIH,GA2qBjB,QAASK,GAAuBC,GAC5B,GAAIC,GAAoC,QAAlBD,CAEtB,OAAO,UAAUE,EAAKC,GAClB,GAAIC,EAAGC,MAAMC,WAAWJ,GACpB,OAAO,CAGX,IAAIK,GAAiBC,CACIC,UAArBN,EAAQO,UAGRF,EAAO,OACPD,EAAkBJ,IAElBK,EAAOL,EAAQO,SACfH,EAAkBJ,EAAQQ,OAKzBC,MAAML,IAAsBA,YAA2BM,QACxDL,EAAO,SAGX,IAAIM,GAAOC,EAAYC,CACvB,QAAQR,EAAKS,eACT,IAAK,OAGD,GAFAH,EAAQ,qBACRC,EAAab,EAAIgB,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js index 4901e390..fee1bf1b 100644 --- a/Src/api.js +++ b/Src/api.js @@ -29,16 +29,18 @@ cleanUpSubscriptions(context); traverseGraph(obj, context); dispose(context); - } + } function traverseGraph(obj, context, level) { var objValues = [], val = obj.peek ? obj.peek() : obj; - if (obj.__kv_traversed === true) { return; } + if (obj.__kv_traversed === true) { + return; + } if (context.options.deep) { - obj.__kv_traversed = true; + obj.__kv_traversed = true; context.flagged.push(obj); } @@ -49,27 +51,30 @@ if (ko.isObservable(obj)) { //make sure it is validatable object - if (!obj.isValid) { obj.extend({ validatable: true }); } + if (!obj.isValid) { + obj.extend({ validatable: true }); + } context.validatables.push(obj); - if(context.options.live && utils.isObservableArray(obj)) { + if (context.options.live && utils.isObservableArray(obj)) { context.subscriptions.push(obj.subscribe(function () { context.graphMonitor.valueHasMutated(); })); - } + } } //get list of values either from array or object but ignore non-objects // and destroyed objects if (val && !val._destroy) { if (utils.isArray(val)) { - objValues = val; - } else if (utils.isObject(val)) { + objValues = val; + } + else if (utils.isObject(val)) { objValues = utils.values(val); - } + } } - //process recurisvely if it is deep grouping + //process recursively if it is deep grouping if (level !== 0) { utils.forEach(objValues, function (observable) { @@ -85,7 +90,9 @@ var errors = []; ko.utils.arrayForEach(array, function (observable) { if (!observable.isValid()) { - errors.push(observable.error()); + // Use peek because we don't want a dependency for 'error' property because it + // changes before 'isValid' does. (Issue #99) + errors.push(observable.error.peek()); } }); return errors; @@ -116,13 +123,13 @@ isInitialized = 1; }, - // backwards compatability + // backwards compatibility configure: function (options) { ko.validation.init(options); }, // resets the config back to its original state reset: ko.validation.configuration.reset, - // recursivly walks a viewModel and creates an object that + // recursively walks a viewModel and creates an object that // provides validation information for the entire viewModel // obj -> the viewModel to walk // options -> { @@ -138,7 +145,7 @@ flagged: [], subscriptions: [], validatables: [] - }; + }; var result = null; @@ -153,7 +160,8 @@ return collectErrors(context.validatables); }); - } else { //if not using observables then every call to error() should traverse the structure + } + else { //if not using observables then every call to error() should traverse the structure result = function () { runTraversal(obj, context); @@ -377,10 +385,10 @@ // we have to do some special things for the pattern validation if (ctx.rule === "pattern" && params instanceof RegExp) { // we need the pure string representation of the RegExpr without the //gi stuff - params = params.source; + params = params.source; } - element.setAttribute(attr, params); + element.setAttribute(attr, params); }, disposeWhenNodeIsRemoved: element }); diff --git a/Tests/api-tests.js b/Tests/api-tests.js index d09708ed..d3fa6db4 100644 --- a/Tests/api-tests.js +++ b/Tests/api-tests.js @@ -205,6 +205,26 @@ QUnit.test('Nested grouping adds items newly inserted into observableArrays to r assert.equal(errors().length, 2, 'validatables are added only once'); }); +QUnit.test('Issue #99 - Grouping notifies with null entries - Observable', function(assert) { + var done = assert.async(); + assert.expect(1); + + var vm = { + items: [ + ko.observable().extend({required: true}), + ko.observable().extend({required: true}) + ] + }; + + var errors = ko.validation.group(vm, {deep: true, observable: true }); + errors.subscribe(function(errors) { + assert.deepEqual(errors, ['This field is required.'], '1 error is reported'); + done(); + }); + + vm.items[0]('1'); +}); + //#endregion //#region validatedObservable From a06f4181e10bf90175311756430481f43fa5b4a7 Mon Sep 17 00:00:00 2001 From: crissdev Date: Wed, 24 Dec 2014 15:00:16 +0200 Subject: [PATCH 115/165] Fix #490 - remove unnecessary call to runTraversal --- Dist/knockout.validation.js | 45 +++++++++++++---------------- Dist/knockout.validation.min.js | 2 +- Dist/knockout.validation.min.js.map | 2 +- Src/api.js | 45 +++++++++++++---------------- 4 files changed, 42 insertions(+), 52 deletions(-) diff --git a/Dist/knockout.validation.js b/Dist/knockout.validation.js index 462cfbb6..dbef8f8c 100644 --- a/Dist/knockout.validation.js +++ b/Dist/knockout.validation.js @@ -236,7 +236,7 @@ kv.configuration = configuration; } if (context.options.deep) { - obj.__kv_traversed = true; + obj.__kv_traversed = true; context.flagged.push(obj); } @@ -303,7 +303,7 @@ kv.configuration = configuration; return; } - //becuase we will be accessing options properties it has to be an object at least + //because we will be accessing options properties it has to be an object at least options = options || {}; //if specific error classes are not provided then apply generic errorClass //it has to be done on option so that options.errorClass can override default @@ -341,26 +341,21 @@ kv.configuration = configuration; flagged: [], subscriptions: [], validatables: [] - }; + }; var result = null; //if using observables then traverse structure once and add observables if (options.observable) { - runTraversal(obj, context); - result = ko.computed(function () { context.graphMonitor(); //register dependency runTraversal(obj, context); - return collectErrors(context.validatables); }); - } else { //if not using observables then every call to error() should traverse the structure result = function () { runTraversal(obj, context); - return collectErrors(context.validatables); }; } @@ -379,7 +374,7 @@ kv.configuration = configuration; }; result.isAnyMessageShown = function () { - var invalidAndModifiedPresent = false; + var invalidAndModifiedPresent; // ensure we have latest changes result(); @@ -517,22 +512,22 @@ kv.configuration = configuration; forEach(kv.configuration.html5Attributes, function (attr) { if (utils.hasAttribute(element, attr)) { - var params = element.getAttribute(attr) || true; - - if (attr === 'min' || attr === 'max') - { - // If we're validating based on the min and max attributes, we'll - // need to know what the 'type' attribute is set to - var typeAttr = element.getAttribute('type'); - if (typeof typeAttr === "undefined" || !typeAttr) - { - // From http://www.w3.org/TR/html-markup/input: - // An input element with no type attribute specified represents the - // same thing as an input element with its type attribute set to "text". - typeAttr = "text"; - } - params = {typeAttr: typeAttr, value: params}; - } + var params = element.getAttribute(attr) || true; + + if (attr === 'min' || attr === 'max') + { + // If we're validating based on the min and max attributes, we'll + // need to know what the 'type' attribute is set to + var typeAttr = element.getAttribute('type'); + if (typeof typeAttr === "undefined" || !typeAttr) + { + // From http://www.w3.org/TR/html-markup/input: + // An input element with no type attribute specified represents the + // same thing as an input element with its type attribute set to "text". + typeAttr = "text"; + } + params = {typeAttr: typeAttr, value: params}; + } kv.addRule(valueAccessor(), { rule: attr, diff --git a/Dist/knockout.validation.min.js b/Dist/knockout.validation.min.js index a0750345..8cf95670 100644 --- a/Dist/knockout.validation.min.js +++ b/Dist/knockout.validation.min.js @@ -7,5 +7,5 @@ =============================================================================== */ -!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||e instanceof Date||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for week input. Should look like '2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for month input. Should look like '2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:h(c.params))?!0:(a.setError(f.formatMessage(c.message||b.message,h(c.params),a)),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,h(c.params),a)),a.__valid__(e)),void a.isValidating(!1)):void a.isValidating(!1)};b.validator(a(),h(c.params||!0),d)}if("undefined"==typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0,live:!1},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},isNumber:function(a){return!isNaN(a)},isObservableArray:function(a){return!!a&&"function"==typeof a.remove&&"function"==typeof a.removeAll&&"function"==typeof a.destroy&&"function"==typeof a.destroyAll&&"function"==typeof a.indexOf&&"function"==typeof a.replace},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return!!(a&&a.rules&&a.isValid&&a.isModified)},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},forEach:function(a,b){if(f.utils.isArray(a))return i(a,b);for(var c in a)a.hasOwnProperty(c)&&b(a[c],c)}}}();var m=function(){function b(a){i(a.subscriptions,function(a){a.dispose()}),a.subscriptions=[]}function c(a){a.options.deep&&(i(a.flagged,function(a){delete a.__kv_traversed}),a.flagged.length=0),a.options.live||b(a)}function d(a,d){d.validatables=[],b(d),e(a,d),c(d)}function e(b,c,d){var f=[],g=b.peek?b.peek():b;b.__kv_traversed!==!0&&(c.options.deep&&(b.__kv_traversed=!0,c.flagged.push(b)),d=void 0!==d?d:c.options.deep?1:-1,a.isObservable(b)&&(b.isValid||b.extend({validatable:!0}),c.validatables.push(b),c.options.live&&n.isObservableArray(b)&&c.subscriptions.push(b.subscribe(function(){c.graphMonitor.valueHasMutated()}))),g&&!g._destroy&&(n.isArray(g)?f=g:n.isObject(g)&&(f=n.values(g))),0!==d&&n.forEach(f,function(a){a&&!a.nodeType&&e(a,c,d+1)}))}function k(a){var b=[];return i(a,function(a){a.isValid()||b.push(a.error.peek())}),b}var l=0,m=f.configuration,n=f.utils;return{init:function(a,b){l>0&&!b||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||m.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||m.errorMessageClass,j(m,a),m.registerExtenders&&f.registerExtenders(),l=1)},configure:function(a){f.init(a)},reset:f.configuration.reset,group:function(b,c){c=j(j({},m.grouping),c);var e={options:c,graphMonitor:a.observable(),flagged:[],subscriptions:[],validatables:[]},f=null;return c.observable?(d(b,e),f=a.computed(function(){return e.graphMonitor(),d(b,e),k(e.validatables)})):f=function(){return d(b,e),k(e.validatables)},f.showAllMessages=function(a){void 0===a&&(a=!0),f(),i(e.validatables,function(b){b.isModified(a)})},f.isAnyMessageShown=function(){var a=!1;return f(),a=!!g.arrayFirst(e.validatables,function(a){return!a.isValid()&&a.isModified()})},f},formatMessage:function(a,b,c){if(n.isObject(b)&&b.typeAttr&&(b=b.value),"function"==typeof a)return a(b,c);var d=h(b)||[];return n.isArray(d)||(d=[d]),a.replace(/{(\d+)}/gi,function(a,b){return"undefined"!=typeof d[b]?d[b]:a})},addRule:function(a,b){return a.extend({validatable:!0}),a.rules.push(b),a},addAnonymousRule:function(a,b){void 0===b.message&&(b.message="Error"),b.onlyIf&&(b.condition=b.onlyIf),f.addRule(a,b)},addExtender:function(b){a.extenders[b]=function(a,c){return c&&(c.message||c.onlyIf)?f.addRule(a,{rule:b,message:c.message,params:n.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(m.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=n.getConfigOptions(a).errorMessageClass,n.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(n.hasAttribute(a,c)){var d=a.getAttribute(c)||!0;if("min"===c||"max"===c){var e=a.getAttribute("type");"undefined"!=typeof e&&e||(e="text"),d={typeAttr:e,value:d}}f.addRule(b(),{rule:c,params:d})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(b,c){var d=c();if(d&&d.rules){var e=d.rules();i(f.configuration.html5Attributes,function(c){var d=g.arrayFirst(e,function(a){return a.rule&&a.rule.toLowerCase()===c.toLowerCase()});d&&a.computed({read:function(){var e=a.unwrap(d.params);"pattern"===d.rule&&e instanceof RegExp&&(e=e.source),b.setAttribute(c,e)},disposeWhenNodeIsRemoved:b})}),e=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var d=function(b,c){if(b&&c)for(var e in c)if(c.hasOwnProperty(e)){var g=c[e];if(b[e]){var i=b[e],j=h(i),k={},l={};for(var m in g)g.hasOwnProperty(m)&&(f.rules[m]?k[m]=g[m]:l[m]=g[m]);if(a.isObservable(i)&&i.extend(k),j&&n.isArray(j))for(var o=0;o0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}."},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address."},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date."},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[-/](?:0?[1-9]|1[012])[-/](?:0?[1-9]|[12][0-9]|3[01])$/.test(a):!0},message:"Please enter a proper date."},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number."},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit."},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number."},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal."},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(c,function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateInputElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.textInput&&f.makeBindingHandlerValidatable("textInput"),f.makeBindingHandlerValidatable("selectedOptions"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),i=(h(d),!1),j=!1;if(null===d||"undefined"==typeof d)throw new Error("Cannot bind validationMessage to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");i=d.isModified(),j=d.isValid();var k=null;(!e.messagesOnModified||i)&&(k=j?null:d.error);var l=!e.messagesOnModified||i?!j:!1,m="none"!==b.style.display;e.allowHtmlMessages?g.setHtml(b,k):a.bindingHandlers.text.update(b,function(){return k}),m&&!l?b.style.display="none":!m&&l&&(b.style.display="")}},a.bindingHandlers.validationElement={update:function(b,c,d){var e=c(),g=f.utils.getConfigOptions(b),i=(h(e),!1),j=!1;if(null===e||"undefined"==typeof e)throw new Error("Cannot bind validationElement to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!e.isValid||!e.isModified)throw new Error("Observable is not validatable");i=e.isModified(),j=e.isValid();var k=function(){var a={},b=!g.decorateElementOnModified||i?!j:!1;return a[g.errorElementClass]=b,a};a.bindingHandlers.css.update(b,k,d),g.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!g.errorsAsTitleOnModified||i,c=f.utils.getOriginalElementTitle(b);return a&&!j?{title:e.error,"data-orig-title":c}:!a||j?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){b.error(a),b.__valid__(!1)},b.clearError=function(){return b.error(null),b.__valid__(!0),b};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){b(),b.rules();return f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified.getSubscriptionsCount()>0&&(b.isModified._subscriptions.change=[]),b.isValidating.getSubscriptionsCount()>0&&(b.isValidating._subscriptions.change=[]),b.__valid__.getSubscriptionsCount()>0&&(b.__valid__._subscriptions.change=[]),g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=c.rule?f.rules[c.rule]:c,b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0},f.localize=function(a){var b;for(b in a)f.rules.hasOwnProperty(b)&&(f.rules[b].message=a[b])},a.applyBindingsWithValidation=function(b,c,d){var e,g=document.body;c&&c.nodeType?(g=c,e=d):e=c,f.init(),e&&(e=j(j({},f.configuration),e),f.utils.setDomData(g,e)),a.applyBindings(b,g)};var n=a.applyBindings;a.applyBindings=function(a,b){f.init(),n(a,b)},a.validatedObservable=function(b,c){if(!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var d=a.observable(b);return d.errors=f.group(b,c),d.isValid=a.observable(0===d.errors().length),a.isObservable(d.errors)?d.errors.subscribe(function(a){d.isValid(0===a.length)}):a.computed(d.errors).subscribe(function(a){d.isValid(0===a.length)}),d}}); +!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||e instanceof Date||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for week input. Should look like '2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for month input. Should look like '2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:h(c.params))?!0:(a.setError(f.formatMessage(c.message||b.message,h(c.params),a)),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,h(c.params),a)),a.__valid__(e)),void a.isValidating(!1)):void a.isValidating(!1)};b.validator(a(),h(c.params||!0),d)}if("undefined"==typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0,live:!1},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},isNumber:function(a){return!isNaN(a)},isObservableArray:function(a){return!!a&&"function"==typeof a.remove&&"function"==typeof a.removeAll&&"function"==typeof a.destroy&&"function"==typeof a.destroyAll&&"function"==typeof a.indexOf&&"function"==typeof a.replace},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return!!(a&&a.rules&&a.isValid&&a.isModified)},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},forEach:function(a,b){if(f.utils.isArray(a))return i(a,b);for(var c in a)a.hasOwnProperty(c)&&b(a[c],c)}}}();var m=function(){function b(a){i(a.subscriptions,function(a){a.dispose()}),a.subscriptions=[]}function c(a){a.options.deep&&(i(a.flagged,function(a){delete a.__kv_traversed}),a.flagged.length=0),a.options.live||b(a)}function d(a,d){d.validatables=[],b(d),e(a,d),c(d)}function e(b,c,d){var f=[],g=b.peek?b.peek():b;b.__kv_traversed!==!0&&(c.options.deep&&(b.__kv_traversed=!0,c.flagged.push(b)),d=void 0!==d?d:c.options.deep?1:-1,a.isObservable(b)&&(b.isValid||b.extend({validatable:!0}),c.validatables.push(b),c.options.live&&n.isObservableArray(b)&&c.subscriptions.push(b.subscribe(function(){c.graphMonitor.valueHasMutated()}))),g&&!g._destroy&&(n.isArray(g)?f=g:n.isObject(g)&&(f=n.values(g))),0!==d&&n.forEach(f,function(a){a&&!a.nodeType&&e(a,c,d+1)}))}function k(a){var b=[];return i(a,function(a){a.isValid()||b.push(a.error.peek())}),b}var l=0,m=f.configuration,n=f.utils;return{init:function(a,b){l>0&&!b||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||m.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||m.errorMessageClass,j(m,a),m.registerExtenders&&f.registerExtenders(),l=1)},configure:function(a){f.init(a)},reset:f.configuration.reset,group:function(b,c){c=j(j({},m.grouping),c);var e={options:c,graphMonitor:a.observable(),flagged:[],subscriptions:[],validatables:[]},f=null;return f=c.observable?a.computed(function(){return e.graphMonitor(),d(b,e),k(e.validatables)}):function(){return d(b,e),k(e.validatables)},f.showAllMessages=function(a){void 0===a&&(a=!0),f(),i(e.validatables,function(b){b.isModified(a)})},f.isAnyMessageShown=function(){var a;return f(),a=!!g.arrayFirst(e.validatables,function(a){return!a.isValid()&&a.isModified()})},f},formatMessage:function(a,b,c){if(n.isObject(b)&&b.typeAttr&&(b=b.value),"function"==typeof a)return a(b,c);var d=h(b)||[];return n.isArray(d)||(d=[d]),a.replace(/{(\d+)}/gi,function(a,b){return"undefined"!=typeof d[b]?d[b]:a})},addRule:function(a,b){return a.extend({validatable:!0}),a.rules.push(b),a},addAnonymousRule:function(a,b){void 0===b.message&&(b.message="Error"),b.onlyIf&&(b.condition=b.onlyIf),f.addRule(a,b)},addExtender:function(b){a.extenders[b]=function(a,c){return c&&(c.message||c.onlyIf)?f.addRule(a,{rule:b,message:c.message,params:n.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(m.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=n.getConfigOptions(a).errorMessageClass,n.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(n.hasAttribute(a,c)){var d=a.getAttribute(c)||!0;if("min"===c||"max"===c){var e=a.getAttribute("type");"undefined"!=typeof e&&e||(e="text"),d={typeAttr:e,value:d}}f.addRule(b(),{rule:c,params:d})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(b,c){var d=c();if(d&&d.rules){var e=d.rules();i(f.configuration.html5Attributes,function(c){var d=g.arrayFirst(e,function(a){return a.rule&&a.rule.toLowerCase()===c.toLowerCase()});d&&a.computed({read:function(){var e=a.unwrap(d.params);"pattern"===d.rule&&e instanceof RegExp&&(e=e.source),b.setAttribute(c,e)},disposeWhenNodeIsRemoved:b})}),e=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var d=function(b,c){if(b&&c)for(var e in c)if(c.hasOwnProperty(e)){var g=c[e];if(b[e]){var i=b[e],j=h(i),k={},l={};for(var m in g)g.hasOwnProperty(m)&&(f.rules[m]?k[m]=g[m]:l[m]=g[m]);if(a.isObservable(i)&&i.extend(k),j&&n.isArray(j))for(var o=0;o0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}."},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address."},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date."},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[-/](?:0?[1-9]|1[012])[-/](?:0?[1-9]|[12][0-9]|3[01])$/.test(a):!0},message:"Please enter a proper date."},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number."},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit."},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number."},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal."},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(c,function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateInputElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.textInput&&f.makeBindingHandlerValidatable("textInput"),f.makeBindingHandlerValidatable("selectedOptions"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),i=(h(d),!1),j=!1;if(null===d||"undefined"==typeof d)throw new Error("Cannot bind validationMessage to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");i=d.isModified(),j=d.isValid();var k=null;(!e.messagesOnModified||i)&&(k=j?null:d.error);var l=!e.messagesOnModified||i?!j:!1,m="none"!==b.style.display;e.allowHtmlMessages?g.setHtml(b,k):a.bindingHandlers.text.update(b,function(){return k}),m&&!l?b.style.display="none":!m&&l&&(b.style.display="")}},a.bindingHandlers.validationElement={update:function(b,c,d){var e=c(),g=f.utils.getConfigOptions(b),i=(h(e),!1),j=!1;if(null===e||"undefined"==typeof e)throw new Error("Cannot bind validationElement to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!e.isValid||!e.isModified)throw new Error("Observable is not validatable");i=e.isModified(),j=e.isValid();var k=function(){var a={},b=!g.decorateElementOnModified||i?!j:!1;return a[g.errorElementClass]=b,a};a.bindingHandlers.css.update(b,k,d),g.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!g.errorsAsTitleOnModified||i,c=f.utils.getOriginalElementTitle(b);return a&&!j?{title:e.error,"data-orig-title":c}:!a||j?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){b.error(a),b.__valid__(!1)},b.clearError=function(){return b.error(null),b.__valid__(!0),b};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){b(),b.rules();return f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified.getSubscriptionsCount()>0&&(b.isModified._subscriptions.change=[]),b.isValidating.getSubscriptionsCount()>0&&(b.isValidating._subscriptions.change=[]),b.__valid__.getSubscriptionsCount()>0&&(b.__valid__._subscriptions.change=[]),g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=c.rule?f.rules[c.rule]:c,b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0},f.localize=function(a){var b;for(b in a)f.rules.hasOwnProperty(b)&&(f.rules[b].message=a[b])},a.applyBindingsWithValidation=function(b,c,d){var e,g=document.body;c&&c.nodeType?(g=c,e=d):e=c,f.init(),e&&(e=j(j({},f.configuration),e),f.utils.setDomData(g,e)),a.applyBindings(b,g)};var n=a.applyBindings;a.applyBindings=function(a,b){f.init(),n(a,b)},a.validatedObservable=function(b,c){if(!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var d=a.observable(b);return d.errors=f.group(b,c),d.isValid=a.observable(0===d.errors().length),a.isObservable(d.errors)?d.errors.subscribe(function(a){d.isValid(0===a.length)}):a.computed(d.errors).subscribe(function(a){d.isValid(0===a.length)}),d}}); //# sourceMappingURL=knockout.validation.min.js.map \ No newline at end of file diff --git a/Dist/knockout.validation.min.js.map b/Dist/knockout.validation.min.js.map index 62d753ad..be0ed5f8 100644 --- a/Dist/knockout.validation.min.js.map +++ b/Dist/knockout.validation.min.js.map @@ -1 +1 @@ -{"version":3,"file":"knockout.validation.min.js","sources":["knockout.validation.js"],"names":["factory","require","exports","module","define","ko","validation","minMaxValidatorFactory","validatorName","isMaxValidation","val","options","kv","utils","isEmptyVal","comparisonValue","type","undefined","typeAttr","value","isNaN","Date","regex","valMatches","comparisonValueMatches","toLowerCase","match","parseFloat","validateSync","observable","rule","ctx","validator","params","unwrap","setError","formatMessage","message","validateAsync","isValidating","callBack","valObj","isValid","msg","__valid__","error","koUtils","unwrapObservable","forEach","arrayForEach","extend","defaults","registerExtenders","messagesOnModified","errorsAsTitle","errorsAsTitleOnModified","messageTemplate","insertMessages","parseInputAttributes","writeInputAttributes","decorateInputElement","decorateElementOnModified","errorClass","errorElementClass","errorMessageClass","allowHtmlMessages","grouping","deep","live","validate","configuration","html5Attributes","html5InputTypes","reset","seedId","getTime","domData","domDataKey","isArray","o","Object","prototype","toString","call","isObject","isNumber","isObservableArray","instance","values","r","i","hasOwnProperty","push","getValue","hasAttribute","node","attr","getAttribute","element","setAttribute","isValidatable","rules","isModified","insertAfter","newNode","parentNode","insertBefore","nextSibling","newId","getConfigOptions","contextFor","setDomData","data","key","getDomData","nodeType","context","getOriginalElementTitle","savedOriginalTitle","currentTitle","title","hasSavedOriginalTitle","async","expr","window","setImmediate","setTimeout","object","callback","prop","api","cleanUpSubscriptions","subscriptions","subscription","dispose","flagged","obj","__kv_traversed","length","runTraversal","validatables","traverseGraph","level","objValues","peek","isObservable","validatable","subscribe","graphMonitor","valueHasMutated","_destroy","collectErrors","array","errors","isInitialized","init","force","configure","group","result","computed","showAllMessages","show","isAnyMessageShown","invalidAndModifiedPresent","arrayFirst","replacements","replace","index","addRule","addAnonymousRule","ruleObj","onlyIf","condition","addExtender","ruleName","extenders","insertValidationMessage","span","document","createElement","className","parseInputValidationAttributes","valueAccessor","currentType","writeInputValidationAttributes","contexts","read","RegExp","source","disposeWhenNodeIsRemoved","makeBindingHandlerValidatable","handlerName","bindingHandlers","allBindingsAccessor","viewModel","bindingContext","setRules","target","definition","ruleDefinitions","targetValue","unwrappedTargetValue","nonRules","required","testVal","String","trim","minLength","normalizedVal","maxLength","step","dif","Math","abs","test","phoneNumber","otherValue","c","collection","external","externalValue","counter","arrayFilter","item","config","validationMessageElement","renderTemplate","field","applyBindingsToNode","validationMessage","validationElement","textInput","update","obsv","Error","isVisible","isCurrentlyVisible","style","display","setHtml","text","cssSettingsAccessor","css","shouldShow","hasModification","data-orig-title","newConfig","enable","validationOptions","throttleEvaluation","throttle","observableArray","clearError","h_change","h_obsValidationTrigger","validateObservable","_disposeValidation","removeAll","getSubscriptionsCount","_subscriptions","ruleContexts","len","localize","msgTranslations","applyBindingsWithValidation","rootNode","body","applyBindings","origApplyBindings","validatedObservable","initialValue"],"mappings":";;;;;;;;;CAUC,SAAUA,GAGgB,kBAAZC,UAA6C,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AG9BrQ,EAAGyQ,oBAAsB,SAAUC,EAAcpQ,GAChD,IAAKC,EAAGC,MAAMuE,SAAS2L,GAAiB,MAAO1Q,GAAGwB,WAAWkP,GAAc7N,QAASgG,aAAa,GAEjG,IAAIwF,GAAOrO,EAAGwB,WAAWkP,EAgBzB,OAfArC,GAAKjF,OAAS7I,EAAGkJ,MAAMiH,EAAcpQ,GACrC+N,EAAKhM,QAAUrC,EAAGwB,WAAoC,IAAzB6M,EAAKjF,SAASf,QAGvCrI,EAAG4I,aAAayF,EAAKjF,QACxBiF,EAAKjF,OAAON,UAAU,SAAUM,GAC9BiF,EAAKhM,QAA0B,IAAlB+G,EAAOf,UAIrBrI,EAAG2J,SAAS0E,EAAKjF,QAAQN,UAAU,SAAUM,GAC5CiF,EAAKhM,QAA0B,IAAlB+G,EAAOf,UAIhBgG"} \ No newline at end of file +{"version":3,"file":"knockout.validation.min.js","sources":["knockout.validation.js"],"names":["factory","require","exports","module","define","ko","validation","minMaxValidatorFactory","validatorName","isMaxValidation","val","options","kv","utils","isEmptyVal","comparisonValue","type","undefined","typeAttr","value","isNaN","Date","regex","valMatches","comparisonValueMatches","toLowerCase","match","parseFloat","validateSync","observable","rule","ctx","validator","params","unwrap","setError","formatMessage","message","validateAsync","isValidating","callBack","valObj","isValid","msg","__valid__","error","koUtils","unwrapObservable","forEach","arrayForEach","extend","defaults","registerExtenders","messagesOnModified","errorsAsTitle","errorsAsTitleOnModified","messageTemplate","insertMessages","parseInputAttributes","writeInputAttributes","decorateInputElement","decorateElementOnModified","errorClass","errorElementClass","errorMessageClass","allowHtmlMessages","grouping","deep","live","validate","configuration","html5Attributes","html5InputTypes","reset","seedId","getTime","domData","domDataKey","isArray","o","Object","prototype","toString","call","isObject","isNumber","isObservableArray","instance","values","r","i","hasOwnProperty","push","getValue","hasAttribute","node","attr","getAttribute","element","setAttribute","isValidatable","rules","isModified","insertAfter","newNode","parentNode","insertBefore","nextSibling","newId","getConfigOptions","contextFor","setDomData","data","key","getDomData","nodeType","context","getOriginalElementTitle","savedOriginalTitle","currentTitle","title","hasSavedOriginalTitle","async","expr","window","setImmediate","setTimeout","object","callback","prop","api","cleanUpSubscriptions","subscriptions","subscription","dispose","flagged","obj","__kv_traversed","length","runTraversal","validatables","traverseGraph","level","objValues","peek","isObservable","validatable","subscribe","graphMonitor","valueHasMutated","_destroy","collectErrors","array","errors","isInitialized","init","force","configure","group","result","computed","showAllMessages","show","isAnyMessageShown","invalidAndModifiedPresent","arrayFirst","replacements","replace","index","addRule","addAnonymousRule","ruleObj","onlyIf","condition","addExtender","ruleName","extenders","insertValidationMessage","span","document","createElement","className","parseInputValidationAttributes","valueAccessor","currentType","writeInputValidationAttributes","contexts","read","RegExp","source","disposeWhenNodeIsRemoved","makeBindingHandlerValidatable","handlerName","bindingHandlers","allBindingsAccessor","viewModel","bindingContext","setRules","target","definition","ruleDefinitions","targetValue","unwrappedTargetValue","nonRules","required","testVal","String","trim","minLength","normalizedVal","maxLength","step","dif","Math","abs","test","phoneNumber","otherValue","c","collection","external","externalValue","counter","arrayFilter","item","config","validationMessageElement","renderTemplate","field","applyBindingsToNode","validationMessage","validationElement","textInput","update","obsv","Error","isVisible","isCurrentlyVisible","style","display","setHtml","text","cssSettingsAccessor","css","shouldShow","hasModification","data-orig-title","newConfig","enable","validationOptions","throttleEvaluation","throttle","observableArray","clearError","h_change","h_obsValidationTrigger","validateObservable","_disposeValidation","removeAll","getSubscriptionsCount","_subscriptions","ruleContexts","len","localize","msgTranslations","applyBindingsWithValidation","rootNode","body","applyBindings","origApplyBindings","validatedObservable","initialValue"],"mappings":";;;;;;;;;CAUC,SAAUA,GAGgB,kBAAZC,UAA6C,gBAAZC,UAA0C,gBAAXC,QAEvEH,EAAQC,QAAQ,YAAaC,SACJ,kBAAXE,SAAyBA,OAAY,IAEnDA,QAAQ,WAAY,WAAYJ,GAGhCA,EAAQK,GAAIA,GAAGC,gBAErB,SAAWD,EAAIH,GAsqBjB,QAASK,GAAuBC,GAC5B,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+N,EAAKhM,QAAUrC,EAAGwB,WAAoC,IAAzB6M,EAAKjF,SAASf,QAGvCrI,EAAG4I,aAAayF,EAAKjF,QACxBiF,EAAKjF,OAAON,UAAU,SAAUM,GAC9BiF,EAAKhM,QAA0B,IAAlB+G,EAAOf,UAIrBrI,EAAG2J,SAAS0E,EAAKjF,QAAQN,UAAU,SAAUM,GAC5CiF,EAAKhM,QAA0B,IAAlB+G,EAAOf,UAIhBgG"} \ No newline at end of file diff --git a/Src/api.js b/Src/api.js index fee1bf1b..9926c490 100644 --- a/Src/api.js +++ b/Src/api.js @@ -40,7 +40,7 @@ } if (context.options.deep) { - obj.__kv_traversed = true; + obj.__kv_traversed = true; context.flagged.push(obj); } @@ -107,7 +107,7 @@ return; } - //becuase we will be accessing options properties it has to be an object at least + //because we will be accessing options properties it has to be an object at least options = options || {}; //if specific error classes are not provided then apply generic errorClass //it has to be done on option so that options.errorClass can override default @@ -145,26 +145,21 @@ flagged: [], subscriptions: [], validatables: [] - }; + }; var result = null; //if using observables then traverse structure once and add observables if (options.observable) { - runTraversal(obj, context); - result = ko.computed(function () { context.graphMonitor(); //register dependency runTraversal(obj, context); - return collectErrors(context.validatables); }); - } else { //if not using observables then every call to error() should traverse the structure result = function () { runTraversal(obj, context); - return collectErrors(context.validatables); }; } @@ -183,7 +178,7 @@ }; result.isAnyMessageShown = function () { - var invalidAndModifiedPresent = false; + var invalidAndModifiedPresent; // ensure we have latest changes result(); @@ -321,22 +316,22 @@ ko.utils.arrayForEach(ko.validation.configuration.html5Attributes, function (attr) { if (utils.hasAttribute(element, attr)) { - var params = element.getAttribute(attr) || true; - - if (attr === 'min' || attr === 'max') - { - // If we're validating based on the min and max attributes, we'll - // need to know what the 'type' attribute is set to - var typeAttr = element.getAttribute('type'); - if (typeof typeAttr === "undefined" || !typeAttr) - { - // From http://www.w3.org/TR/html-markup/input: - // An input element with no type attribute specified represents the - // same thing as an input element with its type attribute set to "text". - typeAttr = "text"; - } - params = {typeAttr: typeAttr, value: params}; - } + var params = element.getAttribute(attr) || true; + + if (attr === 'min' || attr === 'max') + { + // If we're validating based on the min and max attributes, we'll + // need to know what the 'type' attribute is set to + var typeAttr = element.getAttribute('type'); + if (typeof typeAttr === "undefined" || !typeAttr) + { + // From http://www.w3.org/TR/html-markup/input: + // An input element with no type attribute specified represents the + // same thing as an input element with its type attribute set to "text". + typeAttr = "text"; + } + params = {typeAttr: typeAttr, value: params}; + } ko.validation.addRule(valueAccessor(), { rule: attr, From c2f6d619d5339ff688c2471490209ebfb9ce8b0e Mon Sep 17 00:00:00 2001 From: aavezel Date: Tue, 4 Mar 2014 19:20:46 +0600 Subject: [PATCH 116/165] Make Russian localization more user friendly Closes #409 --- Localization/ru-RU.js | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/Localization/ru-RU.js b/Localization/ru-RU.js index 1f434917..125de265 100644 --- a/Localization/ru-RU.js +++ b/Localization/ru-RU.js @@ -20,20 +20,20 @@ */ ko.validation.localize({ - required: 'Необходимо заполнить это поле.', - min: 'Значение должно быть больше или равно {0}.', - max: 'Значение должно быть меньше или равно {0}.', - minLength: 'Длина поля должна быть не меньше {0} символов.', - maxLength: 'Длина поля должна быть не больше {0} символов.', - pattern: 'Пожалуйста проверьте это поле.', - step: 'Значение поле должно изменяться с шагом {0}', - email: 'Введите в поле правильный адрес email', - date: 'Пожалуйста введите правильную дату', - dateISO: 'Пожалуйста введите правильную дату в формате ISO', - number: 'Поле должно содержать число', - digit: 'Поле должно содержать цифры', - phoneUS: 'Поле должно содержать правильный номер телефона', + required: 'Пожалуйста, заполните это поле.', + min: 'Пожалуйста, введите число большее или равное {0}.', + max: 'Пожалуйста, введите число меньшее или равное {0}.', + minLength: 'Пожалуйста, введите по крайней мере {0} символов.', + maxLength: 'Пожалуйста, введите не больше чем {0} символов.', + pattern: 'Пожалуйста, проверьте это поле.', + step: 'Значение должно быть кратным {0}', + email: 'Пожалуйста, укажите здесь правильный адрес электронной почты', + date: 'Пожалуйста, введите правильную дату', + dateISO: 'Пожалуйста, введите правильную дату в формате ISO', + number: 'Пожалуйста, введите число', + digit: 'Пожалуйста, введите цифры', + phoneUS: 'Пожалуйста, укажите правильный телефонный номер', equal: 'Значения должны быть равны', - notEqual: 'Пожалуйста выберите другое значение.', - unique: 'Значение должно быть уникальным.' -}); \ No newline at end of file + notEqual: 'Пожалуйста, выберите другое значение.', + unique: 'Пожалуйста, укажите уникальное значение.' +}); From be74432bd978c9c7b536887ce24a614a8ec157e7 Mon Sep 17 00:00:00 2001 From: crissdev Date: Sat, 27 Dec 2014 01:44:34 +0200 Subject: [PATCH 117/165] Fix #494 - Grouping over validatedObservable objects is not possible --- Dist/knockout.validation.js | 16 ++-- Dist/knockout.validation.min.js | 2 +- Dist/knockout.validation.min.js.map | 2 +- Src/api.js | 16 ++-- Tests/api-tests.js | 139 ++++++++++++++++++++++++++++ 5 files changed, 159 insertions(+), 16 deletions(-) diff --git a/Dist/knockout.validation.js b/Dist/knockout.validation.js index dbef8f8c..975eaacc 100644 --- a/Dist/knockout.validation.js +++ b/Dist/knockout.validation.js @@ -245,9 +245,9 @@ kv.configuration = configuration; // if object is observable then add it to the list if (ko.isObservable(obj)) { - - //make sure it is validatable object - if (!obj.isValid) { + // ensure it's validatable but don't extend validatedObservable because it + // would overwrite isValid property. + if (!obj.errors && !utils.isValidatable(obj)) { obj.extend({ validatable: true }); } context.validatables.push(obj); @@ -273,7 +273,6 @@ kv.configuration = configuration; //process recursively if it is deep grouping if (level !== 0) { utils.forEach(objValues, function (observable) { - //but not falsy things and not HTML Elements if (observable && !observable.nodeType) { traverseGraph(observable, context, level + 1); @@ -285,7 +284,8 @@ kv.configuration = configuration; function collectErrors(array) { var errors = []; forEach(array, function (observable) { - if (!observable.isValid()) { + // Do not collect validatedObservable errors + if (utils.isValidatable(observable) && !observable.isValid()) { // Use peek because we don't want a dependency for 'error' property because it // changes before 'isValid' does. (Issue #99) errors.push(observable.error.peek()); @@ -369,7 +369,9 @@ kv.configuration = configuration; result(); forEach(context.validatables, function (observable) { - observable.isModified(show); + if (utils.isValidatable(observable)) { + observable.isModified(show); + } }); }; @@ -380,7 +382,7 @@ kv.configuration = configuration; result(); invalidAndModifiedPresent = !!koUtils.arrayFirst(context.validatables, function (observable) { - return !observable.isValid() && observable.isModified(); + return utils.isValidatable(observable) && !observable.isValid() && observable.isModified(); }); return invalidAndModifiedPresent; }; diff --git a/Dist/knockout.validation.min.js b/Dist/knockout.validation.min.js index 8cf95670..20316090 100644 --- a/Dist/knockout.validation.min.js +++ b/Dist/knockout.validation.min.js @@ -7,5 +7,5 @@ =============================================================================== */ -!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||e instanceof Date||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for week input. Should look like '2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for month input. Should look like '2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:h(c.params))?!0:(a.setError(f.formatMessage(c.message||b.message,h(c.params),a)),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,h(c.params),a)),a.__valid__(e)),void a.isValidating(!1)):void a.isValidating(!1)};b.validator(a(),h(c.params||!0),d)}if("undefined"==typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0,live:!1},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},isNumber:function(a){return!isNaN(a)},isObservableArray:function(a){return!!a&&"function"==typeof a.remove&&"function"==typeof a.removeAll&&"function"==typeof a.destroy&&"function"==typeof a.destroyAll&&"function"==typeof a.indexOf&&"function"==typeof a.replace},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return!!(a&&a.rules&&a.isValid&&a.isModified)},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},forEach:function(a,b){if(f.utils.isArray(a))return i(a,b);for(var c in a)a.hasOwnProperty(c)&&b(a[c],c)}}}();var m=function(){function b(a){i(a.subscriptions,function(a){a.dispose()}),a.subscriptions=[]}function c(a){a.options.deep&&(i(a.flagged,function(a){delete a.__kv_traversed}),a.flagged.length=0),a.options.live||b(a)}function d(a,d){d.validatables=[],b(d),e(a,d),c(d)}function e(b,c,d){var f=[],g=b.peek?b.peek():b;b.__kv_traversed!==!0&&(c.options.deep&&(b.__kv_traversed=!0,c.flagged.push(b)),d=void 0!==d?d:c.options.deep?1:-1,a.isObservable(b)&&(b.isValid||b.extend({validatable:!0}),c.validatables.push(b),c.options.live&&n.isObservableArray(b)&&c.subscriptions.push(b.subscribe(function(){c.graphMonitor.valueHasMutated()}))),g&&!g._destroy&&(n.isArray(g)?f=g:n.isObject(g)&&(f=n.values(g))),0!==d&&n.forEach(f,function(a){a&&!a.nodeType&&e(a,c,d+1)}))}function k(a){var b=[];return i(a,function(a){a.isValid()||b.push(a.error.peek())}),b}var l=0,m=f.configuration,n=f.utils;return{init:function(a,b){l>0&&!b||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||m.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||m.errorMessageClass,j(m,a),m.registerExtenders&&f.registerExtenders(),l=1)},configure:function(a){f.init(a)},reset:f.configuration.reset,group:function(b,c){c=j(j({},m.grouping),c);var e={options:c,graphMonitor:a.observable(),flagged:[],subscriptions:[],validatables:[]},f=null;return f=c.observable?a.computed(function(){return e.graphMonitor(),d(b,e),k(e.validatables)}):function(){return d(b,e),k(e.validatables)},f.showAllMessages=function(a){void 0===a&&(a=!0),f(),i(e.validatables,function(b){b.isModified(a)})},f.isAnyMessageShown=function(){var a;return f(),a=!!g.arrayFirst(e.validatables,function(a){return!a.isValid()&&a.isModified()})},f},formatMessage:function(a,b,c){if(n.isObject(b)&&b.typeAttr&&(b=b.value),"function"==typeof a)return a(b,c);var d=h(b)||[];return n.isArray(d)||(d=[d]),a.replace(/{(\d+)}/gi,function(a,b){return"undefined"!=typeof d[b]?d[b]:a})},addRule:function(a,b){return a.extend({validatable:!0}),a.rules.push(b),a},addAnonymousRule:function(a,b){void 0===b.message&&(b.message="Error"),b.onlyIf&&(b.condition=b.onlyIf),f.addRule(a,b)},addExtender:function(b){a.extenders[b]=function(a,c){return c&&(c.message||c.onlyIf)?f.addRule(a,{rule:b,message:c.message,params:n.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(m.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=n.getConfigOptions(a).errorMessageClass,n.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(n.hasAttribute(a,c)){var d=a.getAttribute(c)||!0;if("min"===c||"max"===c){var e=a.getAttribute("type");"undefined"!=typeof e&&e||(e="text"),d={typeAttr:e,value:d}}f.addRule(b(),{rule:c,params:d})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(b,c){var d=c();if(d&&d.rules){var e=d.rules();i(f.configuration.html5Attributes,function(c){var d=g.arrayFirst(e,function(a){return a.rule&&a.rule.toLowerCase()===c.toLowerCase()});d&&a.computed({read:function(){var e=a.unwrap(d.params);"pattern"===d.rule&&e instanceof RegExp&&(e=e.source),b.setAttribute(c,e)},disposeWhenNodeIsRemoved:b})}),e=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var d=function(b,c){if(b&&c)for(var e in c)if(c.hasOwnProperty(e)){var g=c[e];if(b[e]){var i=b[e],j=h(i),k={},l={};for(var m in g)g.hasOwnProperty(m)&&(f.rules[m]?k[m]=g[m]:l[m]=g[m]);if(a.isObservable(i)&&i.extend(k),j&&n.isArray(j))for(var o=0;o0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}."},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address."},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date."},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[-/](?:0?[1-9]|1[012])[-/](?:0?[1-9]|[12][0-9]|3[01])$/.test(a):!0},message:"Please enter a proper date."},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number."},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit."},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number."},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal."},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(c,function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateInputElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.textInput&&f.makeBindingHandlerValidatable("textInput"),f.makeBindingHandlerValidatable("selectedOptions"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),i=(h(d),!1),j=!1;if(null===d||"undefined"==typeof d)throw new Error("Cannot bind validationMessage to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");i=d.isModified(),j=d.isValid();var k=null;(!e.messagesOnModified||i)&&(k=j?null:d.error);var l=!e.messagesOnModified||i?!j:!1,m="none"!==b.style.display;e.allowHtmlMessages?g.setHtml(b,k):a.bindingHandlers.text.update(b,function(){return k}),m&&!l?b.style.display="none":!m&&l&&(b.style.display="")}},a.bindingHandlers.validationElement={update:function(b,c,d){var e=c(),g=f.utils.getConfigOptions(b),i=(h(e),!1),j=!1;if(null===e||"undefined"==typeof e)throw new Error("Cannot bind validationElement to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!e.isValid||!e.isModified)throw new Error("Observable is not validatable");i=e.isModified(),j=e.isValid();var k=function(){var a={},b=!g.decorateElementOnModified||i?!j:!1;return a[g.errorElementClass]=b,a};a.bindingHandlers.css.update(b,k,d),g.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!g.errorsAsTitleOnModified||i,c=f.utils.getOriginalElementTitle(b);return a&&!j?{title:e.error,"data-orig-title":c}:!a||j?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){b.error(a),b.__valid__(!1)},b.clearError=function(){return b.error(null),b.__valid__(!0),b};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){b(),b.rules();return f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified.getSubscriptionsCount()>0&&(b.isModified._subscriptions.change=[]),b.isValidating.getSubscriptionsCount()>0&&(b.isValidating._subscriptions.change=[]),b.__valid__.getSubscriptionsCount()>0&&(b.__valid__._subscriptions.change=[]),g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=c.rule?f.rules[c.rule]:c,b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0},f.localize=function(a){var b;for(b in a)f.rules.hasOwnProperty(b)&&(f.rules[b].message=a[b])},a.applyBindingsWithValidation=function(b,c,d){var e,g=document.body;c&&c.nodeType?(g=c,e=d):e=c,f.init(),e&&(e=j(j({},f.configuration),e),f.utils.setDomData(g,e)),a.applyBindings(b,g)};var n=a.applyBindings;a.applyBindings=function(a,b){f.init(),n(a,b)},a.validatedObservable=function(b,c){if(!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var d=a.observable(b);return d.errors=f.group(b,c),d.isValid=a.observable(0===d.errors().length),a.isObservable(d.errors)?d.errors.subscribe(function(a){d.isValid(0===a.length)}):a.computed(d.errors).subscribe(function(a){d.isValid(0===a.length)}),d}}); +!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||e instanceof Date||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for week input. Should look like '2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for month input. Should look like '2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:h(c.params))?!0:(a.setError(f.formatMessage(c.message||b.message,h(c.params),a)),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,h(c.params),a)),a.__valid__(e)),void a.isValidating(!1)):void a.isValidating(!1)};b.validator(a(),h(c.params||!0),d)}if("undefined"==typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0,live:!1},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},isNumber:function(a){return!isNaN(a)},isObservableArray:function(a){return!!a&&"function"==typeof a.remove&&"function"==typeof a.removeAll&&"function"==typeof a.destroy&&"function"==typeof a.destroyAll&&"function"==typeof a.indexOf&&"function"==typeof a.replace},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return!!(a&&a.rules&&a.isValid&&a.isModified)},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},forEach:function(a,b){if(f.utils.isArray(a))return i(a,b);for(var c in a)a.hasOwnProperty(c)&&b(a[c],c)}}}();var m=function(){function b(a){i(a.subscriptions,function(a){a.dispose()}),a.subscriptions=[]}function c(a){a.options.deep&&(i(a.flagged,function(a){delete a.__kv_traversed}),a.flagged.length=0),a.options.live||b(a)}function d(a,d){d.validatables=[],b(d),e(a,d),c(d)}function e(b,c,d){var f=[],g=b.peek?b.peek():b;b.__kv_traversed!==!0&&(c.options.deep&&(b.__kv_traversed=!0,c.flagged.push(b)),d=void 0!==d?d:c.options.deep?1:-1,a.isObservable(b)&&(b.errors||n.isValidatable(b)||b.extend({validatable:!0}),c.validatables.push(b),c.options.live&&n.isObservableArray(b)&&c.subscriptions.push(b.subscribe(function(){c.graphMonitor.valueHasMutated()}))),g&&!g._destroy&&(n.isArray(g)?f=g:n.isObject(g)&&(f=n.values(g))),0!==d&&n.forEach(f,function(a){a&&!a.nodeType&&e(a,c,d+1)}))}function k(a){var b=[];return i(a,function(a){n.isValidatable(a)&&!a.isValid()&&b.push(a.error.peek())}),b}var l=0,m=f.configuration,n=f.utils;return{init:function(a,b){l>0&&!b||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||m.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||m.errorMessageClass,j(m,a),m.registerExtenders&&f.registerExtenders(),l=1)},configure:function(a){f.init(a)},reset:f.configuration.reset,group:function(b,c){c=j(j({},m.grouping),c);var e={options:c,graphMonitor:a.observable(),flagged:[],subscriptions:[],validatables:[]},f=null;return f=c.observable?a.computed(function(){return e.graphMonitor(),d(b,e),k(e.validatables)}):function(){return d(b,e),k(e.validatables)},f.showAllMessages=function(a){void 0===a&&(a=!0),f(),i(e.validatables,function(b){n.isValidatable(b)&&b.isModified(a)})},f.isAnyMessageShown=function(){var a;return f(),a=!!g.arrayFirst(e.validatables,function(a){return n.isValidatable(a)&&!a.isValid()&&a.isModified()})},f},formatMessage:function(a,b,c){if(n.isObject(b)&&b.typeAttr&&(b=b.value),"function"==typeof a)return a(b,c);var d=h(b)||[];return n.isArray(d)||(d=[d]),a.replace(/{(\d+)}/gi,function(a,b){return"undefined"!=typeof d[b]?d[b]:a})},addRule:function(a,b){return a.extend({validatable:!0}),a.rules.push(b),a},addAnonymousRule:function(a,b){void 0===b.message&&(b.message="Error"),b.onlyIf&&(b.condition=b.onlyIf),f.addRule(a,b)},addExtender:function(b){a.extenders[b]=function(a,c){return c&&(c.message||c.onlyIf)?f.addRule(a,{rule:b,message:c.message,params:n.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(m.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=n.getConfigOptions(a).errorMessageClass,n.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(n.hasAttribute(a,c)){var d=a.getAttribute(c)||!0;if("min"===c||"max"===c){var e=a.getAttribute("type");"undefined"!=typeof e&&e||(e="text"),d={typeAttr:e,value:d}}f.addRule(b(),{rule:c,params:d})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(b,c){var d=c();if(d&&d.rules){var e=d.rules();i(f.configuration.html5Attributes,function(c){var d=g.arrayFirst(e,function(a){return a.rule&&a.rule.toLowerCase()===c.toLowerCase()});d&&a.computed({read:function(){var e=a.unwrap(d.params);"pattern"===d.rule&&e instanceof RegExp&&(e=e.source),b.setAttribute(c,e)},disposeWhenNodeIsRemoved:b})}),e=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var d=function(b,c){if(b&&c)for(var e in c)if(c.hasOwnProperty(e)){var g=c[e];if(b[e]){var i=b[e],j=h(i),k={},l={};for(var m in g)g.hasOwnProperty(m)&&(f.rules[m]?k[m]=g[m]:l[m]=g[m]);if(a.isObservable(i)&&i.extend(k),j&&n.isArray(j))for(var o=0;o0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}."},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address."},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date."},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[-/](?:0?[1-9]|1[012])[-/](?:0?[1-9]|[12][0-9]|3[01])$/.test(a):!0},message:"Please enter a proper date."},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number."},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit."},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number."},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal."},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(c,function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateInputElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.textInput&&f.makeBindingHandlerValidatable("textInput"),f.makeBindingHandlerValidatable("selectedOptions"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),i=(h(d),!1),j=!1;if(null===d||"undefined"==typeof d)throw new Error("Cannot bind validationMessage to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");i=d.isModified(),j=d.isValid();var k=null;(!e.messagesOnModified||i)&&(k=j?null:d.error);var l=!e.messagesOnModified||i?!j:!1,m="none"!==b.style.display;e.allowHtmlMessages?g.setHtml(b,k):a.bindingHandlers.text.update(b,function(){return k}),m&&!l?b.style.display="none":!m&&l&&(b.style.display="")}},a.bindingHandlers.validationElement={update:function(b,c,d){var e=c(),g=f.utils.getConfigOptions(b),i=(h(e),!1),j=!1;if(null===e||"undefined"==typeof e)throw new Error("Cannot bind validationElement to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!e.isValid||!e.isModified)throw new Error("Observable is not validatable");i=e.isModified(),j=e.isValid();var k=function(){var a={},b=!g.decorateElementOnModified||i?!j:!1;return a[g.errorElementClass]=b,a};a.bindingHandlers.css.update(b,k,d),g.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!g.errorsAsTitleOnModified||i,c=f.utils.getOriginalElementTitle(b);return a&&!j?{title:e.error,"data-orig-title":c}:!a||j?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){b.error(a),b.__valid__(!1)},b.clearError=function(){return b.error(null),b.__valid__(!0),b};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){b(),b.rules();return f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified.getSubscriptionsCount()>0&&(b.isModified._subscriptions.change=[]),b.isValidating.getSubscriptionsCount()>0&&(b.isValidating._subscriptions.change=[]),b.__valid__.getSubscriptionsCount()>0&&(b.__valid__._subscriptions.change=[]),g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=c.rule?f.rules[c.rule]:c,b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0},f.localize=function(a){var b;for(b in a)f.rules.hasOwnProperty(b)&&(f.rules[b].message=a[b])},a.applyBindingsWithValidation=function(b,c,d){var e,g=document.body;c&&c.nodeType?(g=c,e=d):e=c,f.init(),e&&(e=j(j({},f.configuration),e),f.utils.setDomData(g,e)),a.applyBindings(b,g)};var n=a.applyBindings;a.applyBindings=function(a,b){f.init(),n(a,b)},a.validatedObservable=function(b,c){if(!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var d=a.observable(b);return d.errors=f.group(b,c),d.isValid=a.observable(0===d.errors().length),a.isObservable(d.errors)?d.errors.subscribe(function(a){d.isValid(0===a.length)}):a.computed(d.errors).subscribe(function(a){d.isValid(0===a.length)}),d}}); //# sourceMappingURL=knockout.validation.min.js.map \ No newline at end of file diff --git a/Dist/knockout.validation.min.js.map b/Dist/knockout.validation.min.js.map index be0ed5f8..df521e6e 100644 --- a/Dist/knockout.validation.min.js.map +++ b/Dist/knockout.validation.min.js.map @@ -1 +1 @@ -{"version":3,"file":"knockout.validation.min.js","sources":["knockout.validation.js"],"names":["factory","require","exports","module","define","ko","validation","minMaxValidatorFactory","validatorName","isMaxValidation","val","options","kv","utils","isEmptyVal","comparisonValue","type","undefined","typeAttr","value","isNaN","Date","regex","valMatches","comparisonValueMatches","toLowerCase","match","parseFloat","validateSync","observable","rule","ctx","validator","params","unwrap","setError","formatMessage","message","validateAsync","isValidating","callBack","valObj","isValid","msg","__valid__","error","koUtils","unwrapObservable","forEach","arrayForEach","extend","defaults","registerExtenders","messagesOnModified","errorsAsTitle","errorsAsTitleOnModified","messageTemplate","insertMessages","parseInputAttributes","writeInputAttributes","decorateInputElement","decorateElementOnModified","errorClass","errorElementClass","errorMessageClass","allowHtmlMessages","grouping","deep","live","validate","configuration","html5Attributes","html5InputTypes","reset","seedId","getTime","domData","domDataKey","isArray","o","Object","prototype","toString","call","isObject","isNumber","isObservableArray","instance","values","r","i","hasOwnProperty","push","getValue","hasAttribute","node","attr","getAttribute","element","setAttribute","isValidatable","rules","isModified","insertAfter","newNode","parentNode","insertBefore","nextSibling","newId","getConfigOptions","contextFor","setDomData","data","key","getDomData","nodeType","context","getOriginalElementTitle","savedOriginalTitle","currentTitle","title","hasSavedOriginalTitle","async","expr","window","setImmediate","setTimeout","object","callback","prop","api","cleanUpSubscriptions","subscriptions","subscription","dispose","flagged","obj","__kv_traversed","length","runTraversal","validatables","traverseGraph","level","objValues","peek","isObservable","validatable","subscribe","graphMonitor","valueHasMutated","_destroy","collectErrors","array","errors","isInitialized","init","force","configure","group","result","computed","showAllMessages","show","isAnyMessageShown","invalidAndModifiedPresent","arrayFirst","replacements","replace","index","addRule","addAnonymousRule","ruleObj","onlyIf","condition","addExtender","ruleName","extenders","insertValidationMessage","span","document","createElement","className","parseInputValidationAttributes","valueAccessor","currentType","writeInputValidationAttributes","contexts","read","RegExp","source","disposeWhenNodeIsRemoved","makeBindingHandlerValidatable","handlerName","bindingHandlers","allBindingsAccessor","viewModel","bindingContext","setRules","target","definition","ruleDefinitions","targetValue","unwrappedTargetValue","nonRules","required","testVal","String","trim","minLength","normalizedVal","maxLength","step","dif","Math","abs","test","phoneNumber","otherValue","c","collection","external","externalValue","counter","arrayFilter","item","config","validationMessageElement","renderTemplate","field","applyBindingsToNode","validationMessage","validationElement","textInput","update","obsv","Error","isVisible","isCurrentlyVisible","style","display","setHtml","text","cssSettingsAccessor","css","shouldShow","hasModification","data-orig-title","newConfig","enable","validationOptions","throttleEvaluation","throttle","observableArray","clearError","h_change","h_obsValidationTrigger","validateObservable","_disposeValidation","removeAll","getSubscriptionsCount","_subscriptions","ruleContexts","len","localize","msgTranslations","applyBindingsWithValidation","rootNode","body","applyBindings","origApplyBindings","validatedObservable","initialValue"],"mappings":";;;;;;;;;CAUC,SAAUA,GAGgB,kBAAZC,UAA6C,gBAAZC,UAA0C,gBAAXC,QAEvEH,EAAQC,QAAQ,YAAaC,SACJ,kBAAXE,SAAyBA,OAAY,IAEnDA,QAAQ,WAAY,WAAYJ,GAGhCA,EAAQK,GAAIA,GAAGC,gBAErB,SAAWD,EAAIH,GAsqBjB,QAASK,GAAuBC,GAC5B,GAAIC,GAAoC,QAAlBD,CAEtB,OAAO,UAAUE,EAAKC,GAClB,GAAIC,EAAGC,MAAMC,WAAWJ,GACpB,OAAO,CAGX,IAAIK,GAAiBC,CACIC,UAArBN,EAAQO,UAGRF,EAAO,OACPD,EAAkBJ,IAElBK,EAAOL,EAAQO,SACfH,EAAkBJ,EAAQQ,OAKzBC,MAAML,IAAsBA,YAA2BM,QACxDL,EAAO,SAGX,IAAIM,GAAOC,EAAYC,CACvB,QAAQR,EAAKS,eACT,IAAK,OAGD,GAFAH,EAAQ,qBACRC,EAAab,EAAIgB,MAAMJ,GACJ,OAAfC,EACA,KAAM,qBAAuBf,EAAgB,+HAKjD,OAFAgB,GAAyBT,EAAgBW,MAAMJ,GAE1CE,EAIDf,EACQc,EAAW,GAAKC,E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MV,eAAe7D,KAC3BlB,EAAGyF,MAAMvE,GAAMO,QAAUmO,EAAgB1O,KAU5CzB,EAAGoQ,4BAA8B,SAAUtE,EAAWuE,EAAU/P,GAC/D,GACCsN,GADGlI,EAAOoF,SAASwF,IAGhBD,IAAYA,EAASvJ,UACxBpB,EAAO2K,EACPzC,EAAStN,GAGTsN,EAASyC,EAGV9P,EAAG+I,OAECsE,IACHA,EAAS/K,EAAOA,KAAWtC,EAAG0D,eAAgB2J,GAC9CrN,EAAGC,MAAMkG,WAAWhB,EAAMkI,IAG3B5N,EAAGuQ,cAAczE,EAAWpG,GAI7B,IAAI8K,GAAoBxQ,EAAGuQ,aAC3BvQ,GAAGuQ,cAAgB,SAAUzE,EAAWuE,GAEvC9P,EAAG+I,OAEHkH,EAAkB1E,EAAWuE,IAG9BrQ,EAAGyQ,oBAAsB,SAAUC,EAAcpQ,GAChD,IAAKC,EAAGC,MAAMuE,SAAS2L,GAAiB,MAAO1Q,GAAGwB,WAAWkP,GAAc7N,QAASgG,aAAa,GAEjG,IAAIwF,GAAOrO,EAAGwB,WAAWkP,EAgBzB,OAfArC,GAAKjF,OAAS7I,EAAGkJ,MAAMiH,EAAcpQ,GACrC+N,EAAKhM,QAAUrC,EAAGwB,WAAoC,IAAzB6M,EAAKjF,SAASf,QAGvCrI,EAAG4I,aAAayF,EAAKjF,QACxBiF,EAAKjF,OAAON,UAAU,SAAUM,GAC9BiF,EAAKhM,QAA0B,IAAlB+G,EAAOf,UAIrBrI,EAAG2J,SAAS0E,EAAKjF,QAAQN,UAAU,SAAUM,GAC5CiF,EAAKhM,QAA0B,IAAlB+G,EAAOf,UAIhBgG"} \ No newline at end of file +{"version":3,"file":"knockout.validation.min.js","sources":["knockout.validation.js"],"names":["factory","require","exports","module","define","ko","validation","minMaxValidatorFactory","validatorName","isMaxValidation","val","options","kv","utils","isEmptyVal","comparisonValue","type","undefined","typeAttr","value","isNaN","Date","regex","valMatches","comparisonValueMatches","toLowerCase","match","parseFloat","validateSync","observable","rule","ctx","validator","params","unwrap","setError","formatMessage","message","validateAsync","isValidating","callBack","valObj","isValid","msg","__valid__","error","koUtils","unwrapObservable","forEach","arrayForEach","extend","defaults","registerExtenders","messagesOnModified","errorsAsTitle","errorsAsTitleOnModified","messageTemplate","insertMessages","parseInputAttributes","writeInputAttributes","decorateInputElement","decorateElementOnModified","errorClass","errorElementClass","errorMessageClass","allowHtmlMessages","grouping","deep","live","validate","configuration","html5Attributes","html5InputTypes","reset","seedId","getTime","domData","domDataKey","isArray","o","Object","prototype","toString","call","isObject","isNumber","isObservableArray","instance","values","r","i","hasOwnProperty","push","getValue","hasAttribute","node","attr","getAttribute","element","setAttribute","isValidatable","rules","isModified","insertAfter","newNode","parentNode","insertBefore","nextSibling","newId","getConfigOptions","contextFor","setDomData","data","key","getDomData","nodeType","context","getOriginalElementTitle","savedOriginalTitle","currentTitle","title","hasSavedOriginalTitle","async","expr","window","setImmediate","setTimeout","object","callback","prop","api","cleanUpSubscriptions","subscriptions","subscription","dispose","flagged","obj","__kv_traversed","length","runTraversal","validatables","traverseGraph","level","objValues","peek","isObservable","errors","validatable","subscribe","graphMonitor","valueHasMutated","_destroy","collectErrors","array","isInitialized","init","force","configure","group","result","computed","showAllMessages","show","isAnyMessageShown","invalidAndModifiedPresent","arrayFirst","replacements","replace","index","addRule","addAnonymousRule","ruleObj","onlyIf","condition","addExtender","ruleName","extenders","insertValidationMessage","span","document","createElement","className","parseInputValidationAttributes","valueAccessor","currentType","writeInputValidationAttributes","contexts","read","RegExp","source","disposeWhenNodeIsRemoved","makeBindingHandlerValidatable","handlerName","bindingHandlers","allBindingsAccessor","viewModel","bindingContext","setRules","target","definition","ruleDefinitions","targetValue","unwrappedTargetValue","nonRules","required","testVal","String","trim","minLength","normalizedVal","maxLength","step","dif","Math","abs","test","phoneNumber","otherValue","c","collection","external","externalValue","counter","arrayFilter","item","config","validationMessageElement","renderTemplate","field","applyBindingsToNode","validationMessage","validationElement","textInput","update","obsv","Error","isVisible","isCurrentlyVisible","style","display","setHtml","text","cssSettingsAccessor","css","shouldShow","hasModification","data-orig-title","newConfig","enable","validationOptions","throttleEvaluation","throttle","observableArray","clearError","h_change","h_obsValidationTrigger","validateObservable","_disposeValidation","removeAll","getSubscriptionsCount","_subscriptions","ruleContexts","len","localize","msgTranslations","applyBindingsWithValidation","rootNode","body","applyBindings","origApplyBindings","validatedObservable","initialValue"],"mappings":";;;;;;;;;CAUC,SAAUA,GAGgB,kBAAZC,UAA6C,gBAAZC,UAA0C,gBAAXC,QAEvEH,EAAQC,QAAQ,YAAaC,SACJ,kBAAXE,SAAyBA,OAAY,IAEnDA,QAAQ,WAAY,WAAYJ,GAGhCA,EAAQK,GAAIA,GAAGC,gBAErB,SAAWD,EAAIH,GAwqBjB,QAASK,GAAuBC,GAC5B,GAAIC,GAAoC,QAAlBD,CAEtB,OAAO,UAAUE,EAAKC,GAClB,GAAIC,EAAGC,MAAMC,WAAWJ,GACpB,OAAO,CAGX,IAAIK,GAAiBC,CACIC,UAArBN,EAAQO,UAGRF,EAAO,OACPD,EAAkBJ,IAElBK,EAAOL,EAAQO,SACfH,EAAkBJ,EAAQQ,OAKzBC,MAAML,IAAsBA,YAA2BM,QACxDL,EAAO,SAGX,IAAIM,GAAOC,EAAYC,CACvB,QAAQR,EAAKS,eACT,IAAK,OAGD,GAFAH,EAAQ,qBACRC,EAAab,EAAIgB,MAAMJ,GACJ,OAAfC,EACA,KAAM,qBAAuBf,EAAgB,+HAKjD,OAFAgB,GAAyBT,EAAgBW,MAAMJ,GAE1CE,EAIDf,EACQc,EAAW,GAAKC,EAAuB,IAEzCD,EAAW,KAAOC,EAAuB,IAAQD,EAAW,IAAMC,EAAuB,GAEvFD,EAAW,GAAKC,EAAuB,IAEzCD,EAAW,KAAOC,EAAuB,IAAQD,EAAW,IAAMC,EAAuB,IAVxF,CAcf,KAAK,QAGD,GAFAF,EAAQ,oBACRC,EAAab,EAAIgB,MAAMJ,GACJ,OAAfC,EACA,KAAM,q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oF,SAASwF,IAGhBD,IAAYA,EAASvJ,UACxBpB,EAAO2K,EACPzC,EAAStN,GAGTsN,EAASyC,EAGV9P,EAAG+I,OAECsE,IACHA,EAAS/K,EAAOA,KAAWtC,EAAG0D,eAAgB2J,GAC9CrN,EAAGC,MAAMkG,WAAWhB,EAAMkI,IAG3B5N,EAAGuQ,cAAczE,EAAWpG,GAI7B,IAAI8K,GAAoBxQ,EAAGuQ,aAC3BvQ,GAAGuQ,cAAgB,SAAUzE,EAAWuE,GAEvC9P,EAAG+I,OAEHkH,EAAkB1E,EAAWuE,IAG9BrQ,EAAGyQ,oBAAsB,SAAUC,EAAcpQ,GAChD,IAAKC,EAAGC,MAAMuE,SAAS2L,GAAiB,MAAO1Q,GAAGwB,WAAWkP,GAAc7N,QAASiG,aAAa,GAEjG,IAAIuF,GAAOrO,EAAGwB,WAAWkP,EAgBzB,OAfArC,GAAKxF,OAAStI,EAAGkJ,MAAMiH,EAAcpQ,GACrC+N,EAAKhM,QAAUrC,EAAGwB,WAAoC,IAAzB6M,EAAKxF,SAASR,QAGvCrI,EAAG4I,aAAayF,EAAKxF,QACxBwF,EAAKxF,OAAOE,UAAU,SAAUF,GAC9BwF,EAAKhM,QAA0B,IAAlBwG,EAAOR,UAIrBrI,EAAG2J,SAAS0E,EAAKxF,QAAQE,UAAU,SAAUF,GAC5CwF,EAAKhM,QAA0B,IAAlBwG,EAAOR,UAIhBgG"} \ No newline at end of file diff --git a/Src/api.js b/Src/api.js index 9926c490..94cccf94 100644 --- a/Src/api.js +++ b/Src/api.js @@ -49,9 +49,9 @@ // if object is observable then add it to the list if (ko.isObservable(obj)) { - - //make sure it is validatable object - if (!obj.isValid) { + // ensure it's validatable but don't extend validatedObservable because it + // would overwrite isValid property. + if (!obj.errors && !utils.isValidatable(obj)) { obj.extend({ validatable: true }); } context.validatables.push(obj); @@ -77,7 +77,6 @@ //process recursively if it is deep grouping if (level !== 0) { utils.forEach(objValues, function (observable) { - //but not falsy things and not HTML Elements if (observable && !observable.nodeType) { traverseGraph(observable, context, level + 1); @@ -89,7 +88,8 @@ function collectErrors(array) { var errors = []; ko.utils.arrayForEach(array, function (observable) { - if (!observable.isValid()) { + // Do not collect validatedObservable errors + if (utils.isValidatable(observable) && !observable.isValid()) { // Use peek because we don't want a dependency for 'error' property because it // changes before 'isValid' does. (Issue #99) errors.push(observable.error.peek()); @@ -173,7 +173,9 @@ result(); ko.utils.arrayForEach(context.validatables, function (observable) { - observable.isModified(show); + if (utils.isValidatable(observable)) { + observable.isModified(show); + } }); }; @@ -184,7 +186,7 @@ result(); invalidAndModifiedPresent = !!ko.utils.arrayFirst(context.validatables, function (observable) { - return !observable.isValid() && observable.isModified(); + return utils.isValidatable(observable) && !observable.isValid() && observable.isModified(); }); return invalidAndModifiedPresent; }; diff --git a/Tests/api-tests.js b/Tests/api-tests.js index d3fa6db4..21bdf899 100644 --- a/Tests/api-tests.js +++ b/Tests/api-tests.js @@ -225,6 +225,145 @@ QUnit.test('Issue #99 - Grouping notifies with null entries - Observable', funct vm.items[0]('1'); }); +QUnit.test('Issue #494 - Grouping over validatedObservable works - Observable', function(assert) { + + assert.expect(11); + + var testObj = { + first: ko.validatedObservable({ + abc: ko.observable('').extend({required: true}) + }), + second: ko.validatedObservable({ + xyz: ko.observable('').extend({required: true}) + }) + }; + + var errors = ko.validation.group(testObj, {deep: true, observable: true}); + + // 'errors' should not be observable + assert.strictEqual(ko.isObservable(errors), true, 'errors is observable'); + + // 'validatedObservable' should not be extended with 'validatable' extender because it + // would overwrite isValid property + assert.strictEqual(ko.validation.utils.isValidatable(testObj.first), false, + 'first validatedObservable is not extended with validatable extender'); + assert.strictEqual(ko.validation.utils.isValidatable(testObj.second), false, + 'second validatedObservable is not extended with validatable extender'); + + // 'errors' returns all messages + assert.deepEqual(errors(), ['This field is required.', 'This field is required.']); + + // validatedObservable has isValid and errors properties + assert.strictEqual(testObj.first.isValid(), false, 'first is not valid'); + assert.deepEqual(testObj.first.errors(), ['This field is required.'], 'message is correct'); + + // Check second validatedObservable as well + assert.strictEqual(testObj.second.isValid(), false, 'second is not valid'); + assert.deepEqual(testObj.second.errors(), ['This field is required.'], 'message is correct'); + + // isAnyMessage shown returns false + assert.strictEqual(errors.isAnyMessageShown(), false, 'no message is shown (isModified == false)'); + + // showAllMessages changes isModified to true + errors.showAllMessages(true); + assert.strictEqual(testObj.first().abc.isModified(), true, 'abc isModified == true'); + assert.strictEqual(testObj.second().xyz.isModified(), true, 'xyz isModified == true'); +}); + +QUnit.test('Issue #494 - Grouping over validatedObservable works - Not Observable', function(assert) { + + assert.expect(11); + + var testObj = { + first: ko.validatedObservable({ + abc: ko.observable('').extend({required: true}) + }), + second: ko.validatedObservable({ + xyz: ko.observable('').extend({required: true}) + }) + }; + + var errors = ko.validation.group(testObj, {deep: true, observable: false}); + + // 'errors' should not be observable + assert.strictEqual(ko.isObservable(errors), false, 'errors is not observable'); + + // 'validatedObservable' should not be extended with 'validatable' extender because it + // would overwrite isValid property + assert.strictEqual(ko.validation.utils.isValidatable(testObj.first), false, + 'first validatedObservable is not extended with validatable extender'); + assert.strictEqual(ko.validation.utils.isValidatable(testObj.second), false, + 'second validatedObservable is not extended with validatable extender'); + + // 'errors' returns all messages + assert.deepEqual(errors(), ['This field is required.', 'This field is required.']); + + // validatedObservable has isValid and errors properties + assert.strictEqual(testObj.first.isValid(), false, 'first is not valid'); + assert.deepEqual(testObj.first.errors(), ['This field is required.'], 'message is correct'); + + // Check second validatedObservable as well + assert.strictEqual(testObj.second.isValid(), false, 'second is not valid'); + assert.deepEqual(testObj.second.errors(), ['This field is required.'], 'message is correct'); + + // isAnyMessage shown returns false + assert.strictEqual(errors.isAnyMessageShown(), false, 'no message is shown (isModified == false)'); + + // showAllMessages changes isModified to true + errors.showAllMessages(true); + assert.strictEqual(testObj.first().abc.isModified(), true, 'abc isModified == true'); + assert.strictEqual(testObj.second().xyz.isModified(), true, 'xyz isModified == true'); +}); + +QUnit.test('Issue #494 - Grouping over validatedObservable works after changing field - Observable', function(assert) { + + assert.expect(12); + + var testObj = { + first: ko.validatedObservable({ + abc: ko.observable('').extend({required: true}) + }), + second: ko.validatedObservable({ + xyz: ko.observable('').extend({required: true}) + }) + }; + + var errors = ko.validation.group(testObj, {deep: true, observable: true}); + + testObj.first().abc('test'); + assert.equal(testObj.first().abc(), 'test', 'abc observable works'); + + // 'errors' should not be observable + assert.strictEqual(ko.isObservable(errors), true, 'errors is observable'); + + // 'validatedObservable' should not be extended with 'validatable' extender because it + // would overwrite isValid property + assert.strictEqual(ko.validation.utils.isValidatable(testObj.first), false, + 'first validatedObservable is not extended with validatable extender'); + assert.strictEqual(ko.validation.utils.isValidatable(testObj.second), false, + 'second validatedObservable is not extended with validatable extender'); + + // 'errors' returns all messages + assert.deepEqual(errors(), ['This field is required.']); + + // validatedObservable has isValid and errors properties + assert.strictEqual(testObj.first.isValid(), true, 'first is valid'); + assert.deepEqual(testObj.first.errors(), [], 'first message is empty'); + + // Check second validatedObservable as well + assert.strictEqual(testObj.second.isValid(), false, 'second is not valid'); + assert.deepEqual(testObj.second.errors(), ['This field is required.'], 'second message is correct'); + + // isAnyMessage shown returns false + assert.strictEqual(errors.isAnyMessageShown(), false, 'no message is shown (isModified == false)'); + + // showAllMessages changes isModified to true + errors.showAllMessages(true); + assert.strictEqual(testObj.first().abc.isModified(), true, 'abc isModified == true'); + assert.strictEqual(testObj.second().xyz.isModified(), true, 'xyz isModified == true'); +}); + + //#endregion //#region validatedObservable From 3dbd84d9d32d186b2a201c9017377309eb9fc13b Mon Sep 17 00:00:00 2001 From: crissdev Date: Wed, 7 Jan 2015 10:32:08 +0200 Subject: [PATCH 118/165] Ensure validatedObservable updates validation errors when value changes This commit also adds an internal method to update the state for the validation group. This method is not intended to be used directly but to provide a way to update the group until a better API will be implemented. Closes #442 Closes #269 Closes #209 --- Dist/knockout.validation.js | 68 ++++++++-- Dist/knockout.validation.min.js | 2 +- Dist/knockout.validation.min.js.map | 2 +- Src/api.js | 20 +++ Src/extenders.js | 11 +- Src/ko.extensions.js | 37 +++-- Tests/api-tests.js | 137 +++++++++++++++++++ Tests/test-runner.htm | 200 ++++++++++++++-------------- 8 files changed, 351 insertions(+), 126 deletions(-) diff --git a/Dist/knockout.validation.js b/Dist/knockout.validation.js index 975eaacc..b6170806 100644 --- a/Dist/knockout.validation.js +++ b/Dist/knockout.validation.js @@ -387,6 +387,26 @@ kv.configuration = configuration; return invalidAndModifiedPresent; }; + + /** + * @private You should not rely on this method being here. + * It's a private method and it may change in the future. + * + * @description Updates the validated object and collects errors from it. + */ + result._updateState = function(newValue) { + if (!utils.isObject(newValue)) { + throw new Error('An object is required.'); + } + obj = newValue; + if (options.observable) { + context.graphMonitor.valueHasMutated(); + } + else { + runTraversal(newValue, context); + return collectErrors(context.validatables); + } + }; return result; }, @@ -1166,7 +1186,7 @@ ko.extenders['validatable'] = function (observable, options) { // Rule Context = { rule: '', params: '', message: '' } observable.rules = ko.observableArray(); //holds the rule Contexts to use as part of validation - //in case async validation is occuring + //in case async validation is occurring observable.isValidating = ko.observable(false); //the true holder of whether the observable is valid or not @@ -1179,8 +1199,17 @@ ko.extenders['validatable'] = function (observable, options) { //manually set error state observable.setError = function (error) { + var previousError = observable.error.peek(); + var previousIsValid = observable.__valid__.peek(); + observable.error(error); observable.__valid__(false); + + if (previousError !== error && !previousIsValid) { + // if the observable was not valid before then isValid will not mutate, + // hence causing any grouping to not display the latest error. + observable.isValid.notifySubscribers(); + } }; //manually clear error state @@ -1380,23 +1409,38 @@ ko.applyBindings = function (viewModel, rootNode) { }; ko.validatedObservable = function (initialValue, options) { - if (!kv.utils.isObject(initialValue)) { return ko.observable(initialValue).extend({ validatable: true }); } + if (!options && !kv.utils.isObject(initialValue)) { + return ko.observable(initialValue).extend({ validatable: true }); + } var obsv = ko.observable(initialValue); - obsv.errors = kv.group(initialValue, options); + obsv.errors = kv.group(kv.utils.isObject(initialValue) ? initialValue : {}, options); obsv.isValid = ko.observable(obsv.errors().length === 0); - if (ko.isObservable(obsv.errors)) { - obsv.errors.subscribe(function (errors) { - obsv.isValid(errors.length === 0); - }); - } - else { - ko.computed(obsv.errors).subscribe(function (errors) { - obsv.isValid(errors.length === 0); - }); + obsv.errors.subscribe(function(errors) { + obsv.isValid(errors.length === 0); + }); + } + else { + ko.computed(obsv.errors).subscribe(function (errors) { + obsv.isValid(errors.length === 0); + }); + } + + obsv.subscribe(function(newValue) { + if (!kv.utils.isObject(newValue)) { + /* + * The validation group works on objects. + * Since the new value is a primitive (scalar, null or undefined) we need + * to create an empty object to pass along. + */ + newValue = {}; } + // Force the group to refresh + obsv.errors._updateState(newValue); + obsv.isValid(obsv.errors().length === 0); + }); return obsv; }; diff --git a/Dist/knockout.validation.min.js b/Dist/knockout.validation.min.js index 20316090..791de686 100644 --- a/Dist/knockout.validation.min.js +++ b/Dist/knockout.validation.min.js @@ -7,5 +7,5 @@ =============================================================================== */ -!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||e instanceof Date||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for week input. Should look like '2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for month input. Should look like '2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:h(c.params))?!0:(a.setError(f.formatMessage(c.message||b.message,h(c.params),a)),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,h(c.params),a)),a.__valid__(e)),void a.isValidating(!1)):void a.isValidating(!1)};b.validator(a(),h(c.params||!0),d)}if("undefined"==typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0,live:!1},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},isNumber:function(a){return!isNaN(a)},isObservableArray:function(a){return!!a&&"function"==typeof a.remove&&"function"==typeof a.removeAll&&"function"==typeof a.destroy&&"function"==typeof a.destroyAll&&"function"==typeof a.indexOf&&"function"==typeof a.replace},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return!!(a&&a.rules&&a.isValid&&a.isModified)},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},forEach:function(a,b){if(f.utils.isArray(a))return i(a,b);for(var c in a)a.hasOwnProperty(c)&&b(a[c],c)}}}();var m=function(){function b(a){i(a.subscriptions,function(a){a.dispose()}),a.subscriptions=[]}function c(a){a.options.deep&&(i(a.flagged,function(a){delete a.__kv_traversed}),a.flagged.length=0),a.options.live||b(a)}function d(a,d){d.validatables=[],b(d),e(a,d),c(d)}function e(b,c,d){var f=[],g=b.peek?b.peek():b;b.__kv_traversed!==!0&&(c.options.deep&&(b.__kv_traversed=!0,c.flagged.push(b)),d=void 0!==d?d:c.options.deep?1:-1,a.isObservable(b)&&(b.errors||n.isValidatable(b)||b.extend({validatable:!0}),c.validatables.push(b),c.options.live&&n.isObservableArray(b)&&c.subscriptions.push(b.subscribe(function(){c.graphMonitor.valueHasMutated()}))),g&&!g._destroy&&(n.isArray(g)?f=g:n.isObject(g)&&(f=n.values(g))),0!==d&&n.forEach(f,function(a){a&&!a.nodeType&&e(a,c,d+1)}))}function k(a){var b=[];return i(a,function(a){n.isValidatable(a)&&!a.isValid()&&b.push(a.error.peek())}),b}var l=0,m=f.configuration,n=f.utils;return{init:function(a,b){l>0&&!b||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||m.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||m.errorMessageClass,j(m,a),m.registerExtenders&&f.registerExtenders(),l=1)},configure:function(a){f.init(a)},reset:f.configuration.reset,group:function(b,c){c=j(j({},m.grouping),c);var e={options:c,graphMonitor:a.observable(),flagged:[],subscriptions:[],validatables:[]},f=null;return f=c.observable?a.computed(function(){return e.graphMonitor(),d(b,e),k(e.validatables)}):function(){return d(b,e),k(e.validatables)},f.showAllMessages=function(a){void 0===a&&(a=!0),f(),i(e.validatables,function(b){n.isValidatable(b)&&b.isModified(a)})},f.isAnyMessageShown=function(){var a;return f(),a=!!g.arrayFirst(e.validatables,function(a){return n.isValidatable(a)&&!a.isValid()&&a.isModified()})},f},formatMessage:function(a,b,c){if(n.isObject(b)&&b.typeAttr&&(b=b.value),"function"==typeof a)return a(b,c);var d=h(b)||[];return n.isArray(d)||(d=[d]),a.replace(/{(\d+)}/gi,function(a,b){return"undefined"!=typeof d[b]?d[b]:a})},addRule:function(a,b){return a.extend({validatable:!0}),a.rules.push(b),a},addAnonymousRule:function(a,b){void 0===b.message&&(b.message="Error"),b.onlyIf&&(b.condition=b.onlyIf),f.addRule(a,b)},addExtender:function(b){a.extenders[b]=function(a,c){return c&&(c.message||c.onlyIf)?f.addRule(a,{rule:b,message:c.message,params:n.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(m.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=n.getConfigOptions(a).errorMessageClass,n.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(n.hasAttribute(a,c)){var d=a.getAttribute(c)||!0;if("min"===c||"max"===c){var e=a.getAttribute("type");"undefined"!=typeof e&&e||(e="text"),d={typeAttr:e,value:d}}f.addRule(b(),{rule:c,params:d})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(b,c){var d=c();if(d&&d.rules){var e=d.rules();i(f.configuration.html5Attributes,function(c){var d=g.arrayFirst(e,function(a){return a.rule&&a.rule.toLowerCase()===c.toLowerCase()});d&&a.computed({read:function(){var e=a.unwrap(d.params);"pattern"===d.rule&&e instanceof RegExp&&(e=e.source),b.setAttribute(c,e)},disposeWhenNodeIsRemoved:b})}),e=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var d=function(b,c){if(b&&c)for(var e in c)if(c.hasOwnProperty(e)){var g=c[e];if(b[e]){var i=b[e],j=h(i),k={},l={};for(var m in g)g.hasOwnProperty(m)&&(f.rules[m]?k[m]=g[m]:l[m]=g[m]);if(a.isObservable(i)&&i.extend(k),j&&n.isArray(j))for(var o=0;o0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}."},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address."},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date."},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[-/](?:0?[1-9]|1[012])[-/](?:0?[1-9]|[12][0-9]|3[01])$/.test(a):!0},message:"Please enter a proper date."},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number."},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit."},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number."},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal."},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(c,function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateInputElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.textInput&&f.makeBindingHandlerValidatable("textInput"),f.makeBindingHandlerValidatable("selectedOptions"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),i=(h(d),!1),j=!1;if(null===d||"undefined"==typeof d)throw new Error("Cannot bind validationMessage to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");i=d.isModified(),j=d.isValid();var k=null;(!e.messagesOnModified||i)&&(k=j?null:d.error);var l=!e.messagesOnModified||i?!j:!1,m="none"!==b.style.display;e.allowHtmlMessages?g.setHtml(b,k):a.bindingHandlers.text.update(b,function(){return k}),m&&!l?b.style.display="none":!m&&l&&(b.style.display="")}},a.bindingHandlers.validationElement={update:function(b,c,d){var e=c(),g=f.utils.getConfigOptions(b),i=(h(e),!1),j=!1;if(null===e||"undefined"==typeof e)throw new Error("Cannot bind validationElement to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!e.isValid||!e.isModified)throw new Error("Observable is not validatable");i=e.isModified(),j=e.isValid();var k=function(){var a={},b=!g.decorateElementOnModified||i?!j:!1;return a[g.errorElementClass]=b,a};a.bindingHandlers.css.update(b,k,d),g.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!g.errorsAsTitleOnModified||i,c=f.utils.getOriginalElementTitle(b);return a&&!j?{title:e.error,"data-orig-title":c}:!a||j?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){b.error(a),b.__valid__(!1)},b.clearError=function(){return b.error(null),b.__valid__(!0),b};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){b(),b.rules();return f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified.getSubscriptionsCount()>0&&(b.isModified._subscriptions.change=[]),b.isValidating.getSubscriptionsCount()>0&&(b.isValidating._subscriptions.change=[]),b.__valid__.getSubscriptionsCount()>0&&(b.__valid__._subscriptions.change=[]),g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=c.rule?f.rules[c.rule]:c,b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0},f.localize=function(a){var b;for(b in a)f.rules.hasOwnProperty(b)&&(f.rules[b].message=a[b])},a.applyBindingsWithValidation=function(b,c,d){var e,g=document.body;c&&c.nodeType?(g=c,e=d):e=c,f.init(),e&&(e=j(j({},f.configuration),e),f.utils.setDomData(g,e)),a.applyBindings(b,g)};var n=a.applyBindings;a.applyBindings=function(a,b){f.init(),n(a,b)},a.validatedObservable=function(b,c){if(!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var d=a.observable(b);return d.errors=f.group(b,c),d.isValid=a.observable(0===d.errors().length),a.isObservable(d.errors)?d.errors.subscribe(function(a){d.isValid(0===a.length)}):a.computed(d.errors).subscribe(function(a){d.isValid(0===a.length)}),d}}); +!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||e instanceof Date||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for week input. Should look like '2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for month input. Should look like '2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:h(c.params))?!0:(a.setError(f.formatMessage(c.message||b.message,h(c.params),a)),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,h(c.params),a)),a.__valid__(e)),void a.isValidating(!1)):void a.isValidating(!1)};b.validator(a(),h(c.params||!0),d)}if("undefined"==typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0,live:!1},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},isNumber:function(a){return!isNaN(a)},isObservableArray:function(a){return!!a&&"function"==typeof a.remove&&"function"==typeof a.removeAll&&"function"==typeof a.destroy&&"function"==typeof a.destroyAll&&"function"==typeof a.indexOf&&"function"==typeof a.replace},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return!!(a&&a.rules&&a.isValid&&a.isModified)},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},forEach:function(a,b){if(f.utils.isArray(a))return i(a,b);for(var c in a)a.hasOwnProperty(c)&&b(a[c],c)}}}();var m=function(){function b(a){i(a.subscriptions,function(a){a.dispose()}),a.subscriptions=[]}function c(a){a.options.deep&&(i(a.flagged,function(a){delete a.__kv_traversed}),a.flagged.length=0),a.options.live||b(a)}function d(a,d){d.validatables=[],b(d),e(a,d),c(d)}function e(b,c,d){var f=[],g=b.peek?b.peek():b;b.__kv_traversed!==!0&&(c.options.deep&&(b.__kv_traversed=!0,c.flagged.push(b)),d=void 0!==d?d:c.options.deep?1:-1,a.isObservable(b)&&(b.errors||n.isValidatable(b)||b.extend({validatable:!0}),c.validatables.push(b),c.options.live&&n.isObservableArray(b)&&c.subscriptions.push(b.subscribe(function(){c.graphMonitor.valueHasMutated()}))),g&&!g._destroy&&(n.isArray(g)?f=g:n.isObject(g)&&(f=n.values(g))),0!==d&&n.forEach(f,function(a){a&&!a.nodeType&&e(a,c,d+1)}))}function k(a){var b=[];return i(a,function(a){n.isValidatable(a)&&!a.isValid()&&b.push(a.error.peek())}),b}var l=0,m=f.configuration,n=f.utils;return{init:function(a,b){l>0&&!b||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||m.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||m.errorMessageClass,j(m,a),m.registerExtenders&&f.registerExtenders(),l=1)},configure:function(a){f.init(a)},reset:f.configuration.reset,group:function(b,c){c=j(j({},m.grouping),c);var e={options:c,graphMonitor:a.observable(),flagged:[],subscriptions:[],validatables:[]},f=null;return f=c.observable?a.computed(function(){return e.graphMonitor(),d(b,e),k(e.validatables)}):function(){return d(b,e),k(e.validatables)},f.showAllMessages=function(a){void 0===a&&(a=!0),f(),i(e.validatables,function(b){n.isValidatable(b)&&b.isModified(a)})},f.isAnyMessageShown=function(){var a;return f(),a=!!g.arrayFirst(e.validatables,function(a){return n.isValidatable(a)&&!a.isValid()&&a.isModified()})},f._updateState=function(a){if(!n.isObject(a))throw new Error("An object is required.");return b=a,c.observable?void e.graphMonitor.valueHasMutated():(d(a,e),k(e.validatables))},f},formatMessage:function(a,b,c){if(n.isObject(b)&&b.typeAttr&&(b=b.value),"function"==typeof a)return a(b,c);var d=h(b)||[];return n.isArray(d)||(d=[d]),a.replace(/{(\d+)}/gi,function(a,b){return"undefined"!=typeof d[b]?d[b]:a})},addRule:function(a,b){return a.extend({validatable:!0}),a.rules.push(b),a},addAnonymousRule:function(a,b){void 0===b.message&&(b.message="Error"),b.onlyIf&&(b.condition=b.onlyIf),f.addRule(a,b)},addExtender:function(b){a.extenders[b]=function(a,c){return c&&(c.message||c.onlyIf)?f.addRule(a,{rule:b,message:c.message,params:n.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(m.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=n.getConfigOptions(a).errorMessageClass,n.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(n.hasAttribute(a,c)){var d=a.getAttribute(c)||!0;if("min"===c||"max"===c){var e=a.getAttribute("type");"undefined"!=typeof e&&e||(e="text"),d={typeAttr:e,value:d}}f.addRule(b(),{rule:c,params:d})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(b,c){var d=c();if(d&&d.rules){var e=d.rules();i(f.configuration.html5Attributes,function(c){var d=g.arrayFirst(e,function(a){return a.rule&&a.rule.toLowerCase()===c.toLowerCase()});d&&a.computed({read:function(){var e=a.unwrap(d.params);"pattern"===d.rule&&e instanceof RegExp&&(e=e.source),b.setAttribute(c,e)},disposeWhenNodeIsRemoved:b})}),e=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var d=function(b,c){if(b&&c)for(var e in c)if(c.hasOwnProperty(e)){var g=c[e];if(b[e]){var i=b[e],j=h(i),k={},l={};for(var m in g)g.hasOwnProperty(m)&&(f.rules[m]?k[m]=g[m]:l[m]=g[m]);if(a.isObservable(i)&&i.extend(k),j&&n.isArray(j))for(var o=0;o0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}."},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address."},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date."},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[-/](?:0?[1-9]|1[012])[-/](?:0?[1-9]|[12][0-9]|3[01])$/.test(a):!0},message:"Please enter a proper date."},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number."},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit."},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number."},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal."},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(c,function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateInputElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.textInput&&f.makeBindingHandlerValidatable("textInput"),f.makeBindingHandlerValidatable("selectedOptions"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),i=(h(d),!1),j=!1;if(null===d||"undefined"==typeof d)throw new Error("Cannot bind validationMessage to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");i=d.isModified(),j=d.isValid();var k=null;(!e.messagesOnModified||i)&&(k=j?null:d.error);var l=!e.messagesOnModified||i?!j:!1,m="none"!==b.style.display;e.allowHtmlMessages?g.setHtml(b,k):a.bindingHandlers.text.update(b,function(){return k}),m&&!l?b.style.display="none":!m&&l&&(b.style.display="")}},a.bindingHandlers.validationElement={update:function(b,c,d){var e=c(),g=f.utils.getConfigOptions(b),i=(h(e),!1),j=!1;if(null===e||"undefined"==typeof e)throw new Error("Cannot bind validationElement to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!e.isValid||!e.isModified)throw new Error("Observable is not validatable");i=e.isModified(),j=e.isValid();var k=function(){var a={},b=!g.decorateElementOnModified||i?!j:!1;return a[g.errorElementClass]=b,a};a.bindingHandlers.css.update(b,k,d),g.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!g.errorsAsTitleOnModified||i,c=f.utils.getOriginalElementTitle(b);return a&&!j?{title:e.error,"data-orig-title":c}:!a||j?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){var c=b.error.peek(),d=b.__valid__.peek();b.error(a),b.__valid__(!1),c===a||d||b.isValid.notifySubscribers()},b.clearError=function(){return b.error(null),b.__valid__(!0),b};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){b(),b.rules();return f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified.getSubscriptionsCount()>0&&(b.isModified._subscriptions.change=[]),b.isValidating.getSubscriptionsCount()>0&&(b.isValidating._subscriptions.change=[]),b.__valid__.getSubscriptionsCount()>0&&(b.__valid__._subscriptions.change=[]),g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=c.rule?f.rules[c.rule]:c,b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0},f.localize=function(a){var b;for(b in a)f.rules.hasOwnProperty(b)&&(f.rules[b].message=a[b])},a.applyBindingsWithValidation=function(b,c,d){var e,g=document.body;c&&c.nodeType?(g=c,e=d):e=c,f.init(),e&&(e=j(j({},f.configuration),e),f.utils.setDomData(g,e)),a.applyBindings(b,g)};var n=a.applyBindings;a.applyBindings=function(a,b){f.init(),n(a,b)},a.validatedObservable=function(b,c){if(!c&&!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var d=a.observable(b);return d.errors=f.group(f.utils.isObject(b)?b:{},c),d.isValid=a.observable(0===d.errors().length),a.isObservable(d.errors)?d.errors.subscribe(function(a){d.isValid(0===a.length)}):a.computed(d.errors).subscribe(function(a){d.isValid(0===a.length)}),d.subscribe(function(a){f.utils.isObject(a)||(a={}),d.errors._updateState(a),d.isValid(0===d.errors().length)}),d}}); //# sourceMappingURL=knockout.validation.min.js.map \ No newline at end of file diff --git a/Dist/knockout.validation.min.js.map b/Dist/knockout.validation.min.js.map index df521e6e..d647672a 100644 --- a/Dist/knockout.validation.min.js.map +++ b/Dist/knockout.validation.min.js.map @@ -1 +1 @@ -{"version":3,"file":"knockout.validation.min.js","sources":["knockout.validation.js"],"names":["factory","require","exports","module","define","ko","validation","minMaxValidatorFactory","validatorName","isMaxValidation","val","options","kv","utils","isEmptyVal","comparisonValue","type","undefined","typeAttr","value","isNaN","Date","regex","valMatches","comparisonValueMatches","toLowerCase","match","parseFloat","validateSync","observable","rule","ctx","validator","params","unwrap","setError","formatMessage","message","validateAsync","isValidating","callBack","valObj","isValid","msg","__valid__","error","koUtils","unwrapObservable","forEach","arrayForEach","extend","defaults","registerExtenders","messagesOnModified","errorsAsTitle","errorsAsTitleOnModified","messageTemplate","insertMessages","parseInputAttributes","writeInputAttributes","decorateInputElement","decorateElementOnModified","errorClass","errorElementClass","errorMessageClass","allowHtmlMessages","grouping","deep","live","validate","configuration","html5Attributes","html5InputTypes","reset","seedId","getTime","domData","domDataKey","isArray","o","Object","prototype","toString","call","isObject","isNumber","isObservableArray","instance","values","r","i","hasOwnProperty","push","getValue","hasAttribute","node","attr","getAttribute","element","setAttribute","isValidatable","rules","isModified","insertAfter","newNode","parentNode","insertBefore","nextSibling","newId","getConfigOptions","contextFor","setDomData","data","key","getDomData","nodeType","context","getOriginalElementTitle","savedOriginalTitle","currentTitle","title","hasSavedOriginalTitle","async","expr","window","setImmediate","setTimeout","object","callback","prop","api","cleanUpSubscriptions","subscriptions","subscription","dispose","flagged","obj","__kv_traversed","length","runTraversal","validatables","traverseGraph","level","objValues","peek","isObservable","errors","validatable","subscribe","graphMonitor","valueHasMutated","_destroy","collectErrors","array","isInitialized","init","force","configure","group","result","computed","showAllMessages","show","isAnyMessageShown","invalidAndModifiedPresent","arrayFirst","replacements","replace","index","addRule","addAnonymousRule","ruleObj","onlyIf","condition","addExtender","ruleName","extenders","insertValidationMessage","span","document","createElement","className","parseInputValidationAttributes","valueAccessor","currentType","writeInputValidationAttributes","contexts","read","RegExp","source","disposeWhenNodeIsRemoved","makeBindingHandlerValidatable","handlerName","bindingHandlers","allBindingsAccessor","viewModel","bindingContext","setRules","target","definition","ruleDefinitions","targetValue","unwrappedTargetValue","nonRules","required","testVal","String","trim","minLength","normalizedVal","maxLength","step","dif","Math","abs","test","phoneNumber","otherValue","c","collection","external","externalValue","counter","arrayFilter","item","config","validationMessageElement","renderTemplate","field","applyBindingsToNode","validationMessage","validationElement","textInput","update","obsv","Error","isVisible","isCurrentlyVisible","style","display","setHtml","text","cssSettingsAccessor","css","shouldShow","hasModification","data-orig-title","newConfig","enable","validationOptions","throttleEvaluation","throttle","observableArray","clearError","h_change","h_obsValidationTrigger","validateObservable","_disposeValidation","removeAll","getSubscriptionsCount","_subscriptions","ruleContexts","len","localize","msgTranslations","applyBindingsWithValidation","rootNode","body","applyBindings","origApplyBindings","validatedObservable","initialValue"],"mappings":";;;;;;;;;CAUC,SAAUA,GAGgB,kBAAZC,UAA6C,gBAAZC,UAA0C,gBAAXC,QAEvEH,EAAQC,QAAQ,YAAaC,SACJ,kBAAXE,SAAyBA,OAAY,IAEnDA,QAAQ,WAAY,WAAYJ,GAGhCA,EAAQK,GAAIA,GAAGC,gBAErB,SAAWD,EAAIH,GAwqBjB,QAASK,GAAuBC,GAC5B,GAAIC,GAAoC,QAAlBD,CAEtB,OAAO,UAAU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B,OAfArC,GAAKxF,OAAStI,EAAGkJ,MAAMiH,EAAcpQ,GACrC+N,EAAKhM,QAAUrC,EAAGwB,WAAoC,IAAzB6M,EAAKxF,SAASR,QAGvCrI,EAAG4I,aAAayF,EAAKxF,QACxBwF,EAAKxF,OAAOE,UAAU,SAAUF,GAC9BwF,EAAKhM,QAA0B,IAAlBwG,EAAOR,UAIrBrI,EAAG2J,SAAS0E,EAAKxF,QAAQE,UAAU,SAAUF,GAC5CwF,EAAKhM,QAA0B,IAAlBwG,EAAOR,UAIhBgG"} \ No newline at end of file +{"version":3,"file":"knockout.validation.min.js","sources":["knockout.validation.js"],"names":["factory","require","exports","module","define","ko","validation","minMaxValidatorFactory","validatorName","isMaxValidation","val","options","kv","utils","isEmptyVal","comparisonValue","type","undefined","typeAttr","value","isNaN","Date","regex","valMatches","comparisonValueMatches","toLowerCase","match","parseFloat","validateSync","observable","rule","ctx","validator","params","unwrap","setError","formatMessage","message","validateAsync","isValidating","callBack","valObj","isValid","msg","__valid__","error","koUtils","unwrapObservable","forEach","arrayForEach","extend","defaults","registerExtenders","messagesOnModified","errorsAsTitle","errorsAsTitleOnModified","messageTemplate","insertMessages","parseInputAttributes","writeInputAttributes","decorateInputElement","decorateElementOnModified","errorClass","errorElementClass","errorMessageClass","allowHtmlMessages","grouping","deep","live","validate","configuration","html5Attributes","html5InputTypes","reset","seedId","getTime","domData","domDataKey","isArray","o","Object","prototype","toString","call","isObject","isNumber","isObservableArray","instance","values","r","i","hasOwnProperty","push","getValue","hasAttribute","node","attr","getAttribute","element","setAttribute","isValidatable","rules","isModified","insertAfter","newNode","parentNode","insertBefore","nextSibling","newId","getConfigOptions","contextFor","setDomData","data","key","getDomData","nodeType","context","getOriginalElementTitle","savedOriginalTitle","currentTitle","title","hasSavedOriginalTitle","async","expr","window","setImmediate","setTimeout","object","callback","prop","api","cleanUpSubscriptions","subscriptions","subscription","dispose","flagged","obj","__kv_traversed","length","runTraversal","validatables","traverseGraph","level","objValues","peek","isObservable","errors","validatable","subscribe","graphMonitor","valueHasMutated","_destroy","collectErrors","array","isInitialized","init","force","configure","group","result","computed","showAllMessages","show","isAnyMessageShown","invalidAndModifiedPresent","arrayFirst","_updateState","newValue","Error","replacements","replace","index","addRule","addAnonymousRule","ruleObj","onlyIf","condition","addExtender","ruleName","extenders","insertValidationMessage","span","document","createElement","className","parseInputValidationAttributes","valueAccessor","currentType","writeInputValidationAttributes","contexts","read","RegExp","source","disposeWhenNodeIsRemoved","makeBindingHandlerValidatable","handlerName","bindingHandlers","allBindingsAccessor","viewModel","bindingContext","setRules","target","definition","ruleDefinitions","targetValue","unwrappedTargetValue","nonRules","required","testVal","String","trim","minLength","normalizedVal","maxLength","step","dif","Math","abs","test","phoneNumber","otherValue","c","collection","external","externalValue","counter","arrayFilter","item","config","validationMessageElement","renderTemplate","field","applyBindingsToNode","validationMessage","validationElement","textInput","update","obsv","isVisible","isCurrentlyVisible","style","display","setHtml","text","cssSettingsAccessor","css","shouldShow","hasModification","data-orig-title","newConfig","enable","validationOptions","throttleEvaluation","throttle","observableArray","previousError","previousIsValid","notifySubscribers","clearError","h_change","h_obsValidationTrigger","validateObservable","_disposeValidation","removeAll","getSubscriptionsCount","_subscriptions","ruleContexts","len","localize","msgTranslations","applyBindingsWithValidation","rootNode","body","applyBindings","origApplyBindings","validatedObservable","initialValue"],"mappings":";;;;;;;;;CAUC,SAAUA,GAGgB,kBAAZC,UAA6C,gBAAZC,UAA0C,gBAAXC,QAEvEH,EAAQC,QAAQ,YAAaC,SACJ,kBAAXE,SAAyBA,OAAY,IAEnDA,QAAQ,WAAY,WAAYJ,GAGhCA,EAAQK,GAAIA,GAAGC,gBAErB,SAAWD,EAAIH,GA4rBjB,QAASK,GAAuBC,GAC5B,GAAIC,GAAoC,QAAlBD,CAEtB,OAAO,UAAUE,EAAKC,GAClB,GAAIC,EAAGC,MAAMC,WAAWJ,GACpB,OAAO,CAGX,IAAIK,GAAiBC,CACIC,UAArBN,EAAQO,UAGRF,EA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AAU3E,EAAWyE,GAEvCnQ,EAAG+I,OAEHuH,EAAkB5E,EAAWyE,IAG9B1Q,EAAG8Q,oBAAsB,SAAUC,EAAczQ,GAChD,IAAKA,IAAYC,EAAGC,MAAMuE,SAASgM,GAClC,MAAO/Q,GAAGwB,WAAWuP,GAAclO,QAASiG,aAAa,GAG1D,IAAI0F,GAAOxO,EAAGwB,WAAWuP,EA6BzB,OA5BAvC,GAAK3F,OAAStI,EAAGkJ,MAAMlJ,EAAGC,MAAMuE,SAASgM,GAAgBA,KAAmBzQ,GAC5EkO,EAAKnM,QAAUrC,EAAGwB,WAAoC,IAAzBgN,EAAK3F,SAASR,QAEvCrI,EAAG4I,aAAa4F,EAAK3F,QACxB2F,EAAK3F,OAAOE,UAAU,SAASF,GAC9B2F,EAAKnM,QAA0B,IAAlBwG,EAAOR,UAIrBrI,EAAG2J,SAAS6E,EAAK3F,QAAQE,UAAU,SAAUF,GAC5C2F,EAAKnM,QAA0B,IAAlBwG,EAAOR,UAItBmG,EAAKzF,UAAU,SAASmB,GAClB3J,EAAGC,MAAMuE,SAASmF,KAMtBA,MAGDsE,EAAK3F,OAAOoB,aAAaC,GACzBsE,EAAKnM,QAAiC,IAAzBmM,EAAK3F,SAASR,UAGrBmG"} \ No newline at end of file diff --git a/Src/api.js b/Src/api.js index 94cccf94..6850fee0 100644 --- a/Src/api.js +++ b/Src/api.js @@ -191,6 +191,26 @@ return invalidAndModifiedPresent; }; + + /** + * @private You should not rely on this method being here. + * It's a private method and it may change in the future. + * + * @description Updates the validated object and collects errors from it. + */ + result._updateState = function(newValue) { + if (!utils.isObject(newValue)) { + throw new Error('An object is required.'); + } + obj = newValue; + if (options.observable) { + context.graphMonitor.valueHasMutated(); + } + else { + runTraversal(newValue, context); + return collectErrors(context.validatables); + } + }; return result; }, diff --git a/Src/extenders.js b/Src/extenders.js index 12ca3c4a..ac40a601 100644 --- a/Src/extenders.js +++ b/Src/extenders.js @@ -50,7 +50,7 @@ ko.extenders['validatable'] = function (observable, options) { // Rule Context = { rule: '', params: '', message: '' } observable.rules = ko.observableArray(); //holds the rule Contexts to use as part of validation - //in case async validation is occuring + //in case async validation is occurring observable.isValidating = ko.observable(false); //the true holder of whether the observable is valid or not @@ -63,8 +63,17 @@ ko.extenders['validatable'] = function (observable, options) { //manually set error state observable.setError = function (error) { + var previousError = observable.error.peek(); + var previousIsValid = observable.__valid__.peek(); + observable.error(error); observable.__valid__(false); + + if (previousError !== error && !previousIsValid) { + // if the observable was not valid before then isValid will not mutate, + // hence causing any grouping to not display the latest error. + observable.isValid.notifySubscribers(); + } }; //manually clear error state diff --git a/Src/ko.extensions.js b/Src/ko.extensions.js index e3de4260..9e07d208 100644 --- a/Src/ko.extensions.js +++ b/Src/ko.extensions.js @@ -37,23 +37,38 @@ ko.applyBindings = function (viewModel, rootNode) { }; ko.validatedObservable = function (initialValue, options) { - if (!ko.validation.utils.isObject(initialValue)) { return ko.observable(initialValue).extend({ validatable: true }); } + if (!options && !ko.validation.utils.isObject(initialValue)) { + return ko.observable(initialValue).extend({ validatable: true }); + } var obsv = ko.observable(initialValue); - obsv.errors = ko.validation.group(initialValue, options); + obsv.errors = ko.validation.group(ko.validation.utils.isObject(initialValue) ? initialValue : {}, options); obsv.isValid = ko.observable(obsv.errors().length === 0); - if (ko.isObservable(obsv.errors)) { - obsv.errors.subscribe(function (errors) { - obsv.isValid(errors.length === 0); - }); - } - else { - ko.computed(obsv.errors).subscribe(function (errors) { - obsv.isValid(errors.length === 0); - }); + obsv.errors.subscribe(function(errors) { + obsv.isValid(errors.length === 0); + }); + } + else { + ko.computed(obsv.errors).subscribe(function (errors) { + obsv.isValid(errors.length === 0); + }); + } + + obsv.subscribe(function(newValue) { + if (!ko.validation.utils.isObject(newValue)) { + /* + * The validation group works on objects. + * Since the new value is a primitive (scalar, null or undefined) we need + * to create an empty object to pass along. + */ + newValue = {}; } + // Force the group to refresh + obsv.errors._updateState(newValue); + obsv.isValid(obsv.errors().length === 0); + }); return obsv; }; diff --git a/Tests/api-tests.js b/Tests/api-tests.js index 21bdf899..6a519987 100644 --- a/Tests/api-tests.js +++ b/Tests/api-tests.js @@ -363,6 +363,64 @@ QUnit.test('Issue #494 - Grouping over validatedObservable works after changing assert.strictEqual(testObj.second().xyz.isModified(), true, 'xyz isModified == true'); }); +QUnit.test('Nested Grouping works after changing view model - Observable (using private method _updateState)', function(assert) { + var vm = { + one: ko.observable().extend({ required: true }), + two: { + one: ko.observable().extend({ required: true }) + }, + three: { + two: { + one: ko.observable().extend({ required: true }) + } + } + }; + + var errors = ko.validation.group(vm, { deep: true, observable: true }); + assert.equal(errors().length, 3, 'Grouping correctly finds 3 invalid properties'); + + // Change view model + vm.four = ko.observable('').extend({required: true}); + errors._updateState(vm); + assert.equal(errors().length, 4, 'Grouping correctly finds 4 invalid properties'); +}); + +QUnit.test('Issue #209 - Grouping works when multiple rules are defined - Observable', function(assert) { + + var vm = { + one: ko.observable().extend({ required: true, digit: true }) + }; + + var errors = ko.validation.group(vm, { observable: true }); + + assert.strictEqual(vm.one.isValid(), false, 'observable is not valid'); + assert.deepEqual(errors(), ['This field is required.'], 'Grouping correctly finds 1 invalid property'); + + vm.one('abc'); + + assert.equal(vm.one.error(), 'Please enter a digit.'); + assert.strictEqual(vm.one.isValid(), false, 'observable is not valid'); + assert.deepEqual(errors(), ['Please enter a digit.'], 'Grouping correctly finds 1 invalid property'); +}); + +QUnit.test('Issue #209 - Grouping works when multiple rules are defined - Not Observable', function(assert) { + + var vm = { + one: ko.observable().extend({ required: true, digit: true }) + }; + + var errors = ko.validation.group(vm, { observable: false }); + + assert.strictEqual(vm.one.isValid(), false, 'observable is not valid'); + assert.deepEqual(errors(), ['This field is required.'], 'Grouping correctly finds 1 invalid property'); + + vm.one('abc'); + + // Due to the fix for #99 this test was failing + assert.equal(vm.one.error(), 'Please enter a digit.'); + assert.strictEqual(vm.one.isValid(), false, 'observable is not valid'); + assert.deepEqual(errors(), ['Please enter a digit.'], 'Grouping correctly finds 1 invalid property'); +}); //#endregion @@ -485,6 +543,85 @@ QUnit.test('Issue #454 - validatedObservable throws when config option grouping. assert.ok(!obj.isValid(), obj.errors()[0]); }); +QUnit.test('validatedObservables updates validation state when its value changes', function(assert) { + + function Identity(name, email) { + this.name = ko.observable(name).extend({required: true}); + this.email = ko.observable(email).extend({required: true, email: true}); + } + var identity = ko.validatedObservable(new Identity('', ''), {observable: true}); + + assert.equal(identity.errors().length, 2, '2 errors reported'); + assert.strictEqual(identity.isValid(), false, 'observable is not valid'); + + identity(new Identity('a', 'b')); + assert.equal(identity.errors().length, 1, '1 error reported'); + assert.equal(identity.errors()[0], 'Please enter a proper email address.', 'expecting error for email rule'); + assert.strictEqual(identity.isValid(), false, 'observable is not valid'); +}); + +QUnit.test('validatedObservables updates validation state when its value changes', function(assert) { + + function Identity(name, email) { + this.name = ko.observable(name).extend({required: true}); + this.email = ko.observable(email).extend({required: true, email: true}); + } + var identity = ko.validatedObservable(new Identity('', ''), {observable: true}); + + assert.equal(identity.errors().length, 2, '2 errors reported'); + assert.strictEqual(identity.isValid(), false, 'observable is not valid'); + + identity(undefined); + assert.equal(identity.errors().length, 0, 'no errors reported'); + assert.strictEqual(identity.isValid(), true, 'observable is valid'); + + identity(new Identity('', 'abc@example.com')); + assert.equal(identity.errors().length, 1, '1 error reported'); + assert.strictEqual(identity.isValid(), false, 'observable is not valid'); + + identity({x: ko.observable('-').extend({digit: true})}); + assert.equal(identity.errors().length, 1, '1 error reported'); + assert.equal(identity.errors()[0], 'Please enter a digit.', '1 error reported'); + assert.strictEqual(identity.isValid(), false, 'observable is not valid'); + + identity(5); + assert.equal(identity(), 5, 'observable still works'); + assert.equal(identity.errors().length, 0, 'no errors reported'); + assert.strictEqual(identity.isValid(), true, 'observable is valid'); +}); + +QUnit.test('validatedObservable works when changing from null to object', function(assert) { + + var testObj = ko.validatedObservable(null, {/*Force grouping*/}); + + assert.strictEqual(testObj.isValid(), true, 'observable is valid'); + assert.equal(testObj.errors().length, 0, 'observable is valid'); + + testObj({ + name: ko.observable('').extend({required: true}) + }); + + assert.strictEqual(testObj.isValid(), false, 'observable is not valid'); + assert.equal(testObj.errors().length, 1, '1 error is reported'); + assert.equal(testObj.errors()[0], 'This field is required.', 'message is correct'); +}); + +QUnit.test('validatedObservable works when changing from undefined to object', function(assert) { + + var testObj = ko.validatedObservable(undefined, {/*Force grouping*/}); + + assert.strictEqual(testObj.isValid(), true, 'observable is valid'); + assert.equal(testObj.errors().length, 0, 'observable is valid'); + + testObj({ + name: ko.observable('').extend({required: true}) + }); + + assert.strictEqual(testObj.isValid(), false, 'observable is not valid'); + assert.equal(testObj.errors().length, 1, '1 error is reported'); + assert.equal(testObj.errors()[0], 'This field is required.', 'message is correct'); +}); + //#endregion //#region setRules Tests diff --git a/Tests/test-runner.htm b/Tests/test-runner.htm index ca82f142..93f80c5b 100644 --- a/Tests/test-runner.htm +++ b/Tests/test-runner.htm @@ -1,121 +1,121 @@  - - - - - - + + + + + + - - - - + + + + - Knockout JS Validation Tests - + Knockout JS Validation Tests + -
      -

      Knockout JS Validation Tests

      -

      -
      -

      -
        -
        test markup, will be hidden
        -
        -
        +
        +

        Knockout JS Validation Tests

        +

        +
        +

        +
          +
          test markup, will be hidden
          +
          +
          -
          -
          - - -
          - User: errors - - -
          - - - -
          - - - - -
          - -
          -
          - - + +
          + User: errors + + +
          + + + +
          + + + + +
          + +
          +
          + + -
          + QUnit.test('Reports Correct Amount of Starting Errors', function(assert) { + var cnt = $('#errorCount').text(); + assert.strictEqual(cnt, '5', 'Init was not called, and the correct number of errors was evaluated'); + }); + }); + +
          From cdce5c3cbf4fedbb0d098243be51b5a4c3d35671 Mon Sep 17 00:00:00 2001 From: crissdev Date: Thu, 8 Jan 2015 00:30:30 +0200 Subject: [PATCH 119/165] Fix #277 - parseInputAttributes option may duplicate rules when enabled --- Dist/knockout.validation.js | 10 ++++++-- Dist/knockout.validation.min.js | 2 +- Dist/knockout.validation.min.js.map | 2 +- Src/api.js | 10 ++++++-- Tests/api-tests.js | 21 +++++++++++++++ Tests/validation-ui-tests.js | 40 +++++++++++++++++++++++++++++ 6 files changed, 79 insertions(+), 6 deletions(-) diff --git a/Dist/knockout.validation.js b/Dist/knockout.validation.js index b6170806..d526e41c 100644 --- a/Dist/knockout.validation.js +++ b/Dist/knockout.validation.js @@ -439,8 +439,14 @@ kv.configuration = configuration; addRule: function (observable, rule) { observable.extend({ validatable: true }); - //push a Rule Context to the observables local array of Rule Contexts - observable.rules.push(rule); + var hasRule = !!koUtils.arrayFirst(observable.rules(), function(item) { + return item.rule && item.rule === rule.rule; + }); + + if (!hasRule) { + //push a Rule Context to the observables local array of Rule Contexts + observable.rules.push(rule); + } return observable; }, diff --git a/Dist/knockout.validation.min.js b/Dist/knockout.validation.min.js index 791de686..90b57e09 100644 --- a/Dist/knockout.validation.min.js +++ b/Dist/knockout.validation.min.js @@ -7,5 +7,5 @@ =============================================================================== */ -!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||e instanceof Date||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for week input. Should look like '2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for month input. Should look like '2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:h(c.params))?!0:(a.setError(f.formatMessage(c.message||b.message,h(c.params),a)),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,h(c.params),a)),a.__valid__(e)),void a.isValidating(!1)):void a.isValidating(!1)};b.validator(a(),h(c.params||!0),d)}if("undefined"==typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0,live:!1},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},isNumber:function(a){return!isNaN(a)},isObservableArray:function(a){return!!a&&"function"==typeof a.remove&&"function"==typeof a.removeAll&&"function"==typeof a.destroy&&"function"==typeof a.destroyAll&&"function"==typeof a.indexOf&&"function"==typeof a.replace},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return!!(a&&a.rules&&a.isValid&&a.isModified)},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},forEach:function(a,b){if(f.utils.isArray(a))return i(a,b);for(var c in a)a.hasOwnProperty(c)&&b(a[c],c)}}}();var m=function(){function b(a){i(a.subscriptions,function(a){a.dispose()}),a.subscriptions=[]}function c(a){a.options.deep&&(i(a.flagged,function(a){delete a.__kv_traversed}),a.flagged.length=0),a.options.live||b(a)}function d(a,d){d.validatables=[],b(d),e(a,d),c(d)}function e(b,c,d){var f=[],g=b.peek?b.peek():b;b.__kv_traversed!==!0&&(c.options.deep&&(b.__kv_traversed=!0,c.flagged.push(b)),d=void 0!==d?d:c.options.deep?1:-1,a.isObservable(b)&&(b.errors||n.isValidatable(b)||b.extend({validatable:!0}),c.validatables.push(b),c.options.live&&n.isObservableArray(b)&&c.subscriptions.push(b.subscribe(function(){c.graphMonitor.valueHasMutated()}))),g&&!g._destroy&&(n.isArray(g)?f=g:n.isObject(g)&&(f=n.values(g))),0!==d&&n.forEach(f,function(a){a&&!a.nodeType&&e(a,c,d+1)}))}function k(a){var b=[];return i(a,function(a){n.isValidatable(a)&&!a.isValid()&&b.push(a.error.peek())}),b}var l=0,m=f.configuration,n=f.utils;return{init:function(a,b){l>0&&!b||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||m.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||m.errorMessageClass,j(m,a),m.registerExtenders&&f.registerExtenders(),l=1)},configure:function(a){f.init(a)},reset:f.configuration.reset,group:function(b,c){c=j(j({},m.grouping),c);var e={options:c,graphMonitor:a.observable(),flagged:[],subscriptions:[],validatables:[]},f=null;return f=c.observable?a.computed(function(){return e.graphMonitor(),d(b,e),k(e.validatables)}):function(){return d(b,e),k(e.validatables)},f.showAllMessages=function(a){void 0===a&&(a=!0),f(),i(e.validatables,function(b){n.isValidatable(b)&&b.isModified(a)})},f.isAnyMessageShown=function(){var a;return f(),a=!!g.arrayFirst(e.validatables,function(a){return n.isValidatable(a)&&!a.isValid()&&a.isModified()})},f._updateState=function(a){if(!n.isObject(a))throw new Error("An object is required.");return b=a,c.observable?void e.graphMonitor.valueHasMutated():(d(a,e),k(e.validatables))},f},formatMessage:function(a,b,c){if(n.isObject(b)&&b.typeAttr&&(b=b.value),"function"==typeof a)return a(b,c);var d=h(b)||[];return n.isArray(d)||(d=[d]),a.replace(/{(\d+)}/gi,function(a,b){return"undefined"!=typeof d[b]?d[b]:a})},addRule:function(a,b){return a.extend({validatable:!0}),a.rules.push(b),a},addAnonymousRule:function(a,b){void 0===b.message&&(b.message="Error"),b.onlyIf&&(b.condition=b.onlyIf),f.addRule(a,b)},addExtender:function(b){a.extenders[b]=function(a,c){return c&&(c.message||c.onlyIf)?f.addRule(a,{rule:b,message:c.message,params:n.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(m.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=n.getConfigOptions(a).errorMessageClass,n.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(n.hasAttribute(a,c)){var d=a.getAttribute(c)||!0;if("min"===c||"max"===c){var e=a.getAttribute("type");"undefined"!=typeof e&&e||(e="text"),d={typeAttr:e,value:d}}f.addRule(b(),{rule:c,params:d})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(b,c){var d=c();if(d&&d.rules){var e=d.rules();i(f.configuration.html5Attributes,function(c){var d=g.arrayFirst(e,function(a){return a.rule&&a.rule.toLowerCase()===c.toLowerCase()});d&&a.computed({read:function(){var e=a.unwrap(d.params);"pattern"===d.rule&&e instanceof RegExp&&(e=e.source),b.setAttribute(c,e)},disposeWhenNodeIsRemoved:b})}),e=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var d=function(b,c){if(b&&c)for(var e in c)if(c.hasOwnProperty(e)){var g=c[e];if(b[e]){var i=b[e],j=h(i),k={},l={};for(var m in g)g.hasOwnProperty(m)&&(f.rules[m]?k[m]=g[m]:l[m]=g[m]);if(a.isObservable(i)&&i.extend(k),j&&n.isArray(j))for(var o=0;o0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}."},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address."},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date."},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[-/](?:0?[1-9]|1[012])[-/](?:0?[1-9]|[12][0-9]|3[01])$/.test(a):!0},message:"Please enter a proper date."},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number."},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit."},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number."},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal."},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(c,function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateInputElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.textInput&&f.makeBindingHandlerValidatable("textInput"),f.makeBindingHandlerValidatable("selectedOptions"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),i=(h(d),!1),j=!1;if(null===d||"undefined"==typeof d)throw new Error("Cannot bind validationMessage to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");i=d.isModified(),j=d.isValid();var k=null;(!e.messagesOnModified||i)&&(k=j?null:d.error);var l=!e.messagesOnModified||i?!j:!1,m="none"!==b.style.display;e.allowHtmlMessages?g.setHtml(b,k):a.bindingHandlers.text.update(b,function(){return k}),m&&!l?b.style.display="none":!m&&l&&(b.style.display="")}},a.bindingHandlers.validationElement={update:function(b,c,d){var e=c(),g=f.utils.getConfigOptions(b),i=(h(e),!1),j=!1;if(null===e||"undefined"==typeof e)throw new Error("Cannot bind validationElement to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!e.isValid||!e.isModified)throw new Error("Observable is not validatable");i=e.isModified(),j=e.isValid();var k=function(){var a={},b=!g.decorateElementOnModified||i?!j:!1;return a[g.errorElementClass]=b,a};a.bindingHandlers.css.update(b,k,d),g.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!g.errorsAsTitleOnModified||i,c=f.utils.getOriginalElementTitle(b);return a&&!j?{title:e.error,"data-orig-title":c}:!a||j?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){var c=b.error.peek(),d=b.__valid__.peek();b.error(a),b.__valid__(!1),c===a||d||b.isValid.notifySubscribers()},b.clearError=function(){return b.error(null),b.__valid__(!0),b};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){b(),b.rules();return f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified.getSubscriptionsCount()>0&&(b.isModified._subscriptions.change=[]),b.isValidating.getSubscriptionsCount()>0&&(b.isValidating._subscriptions.change=[]),b.__valid__.getSubscriptionsCount()>0&&(b.__valid__._subscriptions.change=[]),g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=c.rule?f.rules[c.rule]:c,b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0},f.localize=function(a){var b;for(b in a)f.rules.hasOwnProperty(b)&&(f.rules[b].message=a[b])},a.applyBindingsWithValidation=function(b,c,d){var e,g=document.body;c&&c.nodeType?(g=c,e=d):e=c,f.init(),e&&(e=j(j({},f.configuration),e),f.utils.setDomData(g,e)),a.applyBindings(b,g)};var n=a.applyBindings;a.applyBindings=function(a,b){f.init(),n(a,b)},a.validatedObservable=function(b,c){if(!c&&!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var d=a.observable(b);return d.errors=f.group(f.utils.isObject(b)?b:{},c),d.isValid=a.observable(0===d.errors().length),a.isObservable(d.errors)?d.errors.subscribe(function(a){d.isValid(0===a.length)}):a.computed(d.errors).subscribe(function(a){d.isValid(0===a.length)}),d.subscribe(function(a){f.utils.isObject(a)||(a={}),d.errors._updateState(a),d.isValid(0===d.errors().length)}),d}}); +!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||e instanceof Date||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for week input. Should look like '2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for month input. Should look like '2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:h(c.params))?!0:(a.setError(f.formatMessage(c.message||b.message,h(c.params),a)),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,h(c.params),a)),a.__valid__(e)),void a.isValidating(!1)):void a.isValidating(!1)};b.validator(a(),h(c.params||!0),d)}if("undefined"==typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0,live:!1},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},isNumber:function(a){return!isNaN(a)},isObservableArray:function(a){return!!a&&"function"==typeof a.remove&&"function"==typeof a.removeAll&&"function"==typeof a.destroy&&"function"==typeof a.destroyAll&&"function"==typeof a.indexOf&&"function"==typeof a.replace},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return!!(a&&a.rules&&a.isValid&&a.isModified)},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},forEach:function(a,b){if(f.utils.isArray(a))return i(a,b);for(var c in a)a.hasOwnProperty(c)&&b(a[c],c)}}}();var m=function(){function b(a){i(a.subscriptions,function(a){a.dispose()}),a.subscriptions=[]}function c(a){a.options.deep&&(i(a.flagged,function(a){delete a.__kv_traversed}),a.flagged.length=0),a.options.live||b(a)}function d(a,d){d.validatables=[],b(d),e(a,d),c(d)}function e(b,c,d){var f=[],g=b.peek?b.peek():b;b.__kv_traversed!==!0&&(c.options.deep&&(b.__kv_traversed=!0,c.flagged.push(b)),d=void 0!==d?d:c.options.deep?1:-1,a.isObservable(b)&&(b.errors||n.isValidatable(b)||b.extend({validatable:!0}),c.validatables.push(b),c.options.live&&n.isObservableArray(b)&&c.subscriptions.push(b.subscribe(function(){c.graphMonitor.valueHasMutated()}))),g&&!g._destroy&&(n.isArray(g)?f=g:n.isObject(g)&&(f=n.values(g))),0!==d&&n.forEach(f,function(a){a&&!a.nodeType&&e(a,c,d+1)}))}function k(a){var b=[];return i(a,function(a){n.isValidatable(a)&&!a.isValid()&&b.push(a.error.peek())}),b}var l=0,m=f.configuration,n=f.utils;return{init:function(a,b){l>0&&!b||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||m.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||m.errorMessageClass,j(m,a),m.registerExtenders&&f.registerExtenders(),l=1)},configure:function(a){f.init(a)},reset:f.configuration.reset,group:function(b,c){c=j(j({},m.grouping),c);var e={options:c,graphMonitor:a.observable(),flagged:[],subscriptions:[],validatables:[]},f=null;return f=c.observable?a.computed(function(){return e.graphMonitor(),d(b,e),k(e.validatables)}):function(){return d(b,e),k(e.validatables)},f.showAllMessages=function(a){void 0===a&&(a=!0),f(),i(e.validatables,function(b){n.isValidatable(b)&&b.isModified(a)})},f.isAnyMessageShown=function(){var a;return f(),a=!!g.arrayFirst(e.validatables,function(a){return n.isValidatable(a)&&!a.isValid()&&a.isModified()})},f._updateState=function(a){if(!n.isObject(a))throw new Error("An object is required.");return b=a,c.observable?void e.graphMonitor.valueHasMutated():(d(a,e),k(e.validatables))},f},formatMessage:function(a,b,c){if(n.isObject(b)&&b.typeAttr&&(b=b.value),"function"==typeof a)return a(b,c);var d=h(b)||[];return n.isArray(d)||(d=[d]),a.replace(/{(\d+)}/gi,function(a,b){return"undefined"!=typeof d[b]?d[b]:a})},addRule:function(a,b){a.extend({validatable:!0});var c=!!g.arrayFirst(a.rules(),function(a){return a.rule&&a.rule===b.rule});return c||a.rules.push(b),a},addAnonymousRule:function(a,b){void 0===b.message&&(b.message="Error"),b.onlyIf&&(b.condition=b.onlyIf),f.addRule(a,b)},addExtender:function(b){a.extenders[b]=function(a,c){return c&&(c.message||c.onlyIf)?f.addRule(a,{rule:b,message:c.message,params:n.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(m.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=n.getConfigOptions(a).errorMessageClass,n.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(n.hasAttribute(a,c)){var d=a.getAttribute(c)||!0;if("min"===c||"max"===c){var e=a.getAttribute("type");"undefined"!=typeof e&&e||(e="text"),d={typeAttr:e,value:d}}f.addRule(b(),{rule:c,params:d})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(b,c){var d=c();if(d&&d.rules){var e=d.rules();i(f.configuration.html5Attributes,function(c){var d=g.arrayFirst(e,function(a){return a.rule&&a.rule.toLowerCase()===c.toLowerCase()});d&&a.computed({read:function(){var e=a.unwrap(d.params);"pattern"===d.rule&&e instanceof RegExp&&(e=e.source),b.setAttribute(c,e)},disposeWhenNodeIsRemoved:b})}),e=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var d=function(b,c){if(b&&c)for(var e in c)if(c.hasOwnProperty(e)){var g=c[e];if(b[e]){var i=b[e],j=h(i),k={},l={};for(var m in g)g.hasOwnProperty(m)&&(f.rules[m]?k[m]=g[m]:l[m]=g[m]);if(a.isObservable(i)&&i.extend(k),j&&n.isArray(j))for(var o=0;o0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}."},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address."},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date."},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[-/](?:0?[1-9]|1[012])[-/](?:0?[1-9]|[12][0-9]|3[01])$/.test(a):!0},message:"Please enter a proper date."},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number."},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit."},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number."},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal."},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(c,function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateInputElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.textInput&&f.makeBindingHandlerValidatable("textInput"),f.makeBindingHandlerValidatable("selectedOptions"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),i=(h(d),!1),j=!1;if(null===d||"undefined"==typeof d)throw new Error("Cannot bind validationMessage to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");i=d.isModified(),j=d.isValid();var k=null;(!e.messagesOnModified||i)&&(k=j?null:d.error);var l=!e.messagesOnModified||i?!j:!1,m="none"!==b.style.display;e.allowHtmlMessages?g.setHtml(b,k):a.bindingHandlers.text.update(b,function(){return k}),m&&!l?b.style.display="none":!m&&l&&(b.style.display="")}},a.bindingHandlers.validationElement={update:function(b,c,d){var e=c(),g=f.utils.getConfigOptions(b),i=(h(e),!1),j=!1;if(null===e||"undefined"==typeof e)throw new Error("Cannot bind validationElement to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!e.isValid||!e.isModified)throw new Error("Observable is not validatable");i=e.isModified(),j=e.isValid();var k=function(){var a={},b=!g.decorateElementOnModified||i?!j:!1;return a[g.errorElementClass]=b,a};a.bindingHandlers.css.update(b,k,d),g.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!g.errorsAsTitleOnModified||i,c=f.utils.getOriginalElementTitle(b);return a&&!j?{title:e.error,"data-orig-title":c}:!a||j?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){var c=b.error.peek(),d=b.__valid__.peek();b.error(a),b.__valid__(!1),c===a||d||b.isValid.notifySubscribers()},b.clearError=function(){return b.error(null),b.__valid__(!0),b};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){b(),b.rules();return f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified.getSubscriptionsCount()>0&&(b.isModified._subscriptions.change=[]),b.isValidating.getSubscriptionsCount()>0&&(b.isValidating._subscriptions.change=[]),b.__valid__.getSubscriptionsCount()>0&&(b.__valid__._subscriptions.change=[]),g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=c.rule?f.rules[c.rule]:c,b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0},f.localize=function(a){var b;for(b in a)f.rules.hasOwnProperty(b)&&(f.rules[b].message=a[b])},a.applyBindingsWithValidation=function(b,c,d){var e,g=document.body;c&&c.nodeType?(g=c,e=d):e=c,f.init(),e&&(e=j(j({},f.configuration),e),f.utils.setDomData(g,e)),a.applyBindings(b,g)};var n=a.applyBindings;a.applyBindings=function(a,b){f.init(),n(a,b)},a.validatedObservable=function(b,c){if(!c&&!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var d=a.observable(b);return d.errors=f.group(f.utils.isObject(b)?b:{},c),d.isValid=a.observable(0===d.errors().length),a.isObservable(d.errors)?d.errors.subscribe(function(a){d.isValid(0===a.length)}):a.computed(d.errors).subscribe(function(a){d.isValid(0===a.length)}),d.subscribe(function(a){f.utils.isObject(a)||(a={}),d.errors._updateState(a),d.isValid(0===d.errors().length)}),d}}); //# sourceMappingURL=knockout.validation.min.js.map \ No newline at end of file diff --git a/Dist/knockout.validation.min.js.map b/Dist/knockout.validation.min.js.map index d647672a..c382b16c 100644 --- a/Dist/knockout.validation.min.js.map +++ b/Dist/knockout.validation.min.js.map @@ -1 +1 @@ -{"version":3,"file":"knockout.validation.min.js","sources":["knockout.validation.js"],"names":["factory","require","exports","module","define","ko","validation","minMaxValidatorFactory","validatorName","isMaxValidation","val","options","kv","utils","isEmptyVal","comparisonValue","type","undefined","typeAttr","value","isNaN","Date","regex","valMatches","comparisonValueMatches","toLowerCase","match","parseFloat","validateSync","observable","rule","ctx","validator","params","unwrap","setError","formatMessage","message","validateAsync","isValidating","callBack","valObj","isValid","msg","__valid__","error","koUtils","unwrapObservable","forEach","arrayForEach","extend","defaults","registerExtenders","messagesOnModified","errorsAsTitle","errorsAsTitleOnModified","messageTemplate","insertMessages","parseInputAttributes","writeInputAttributes","decorateInputElement","decorateElementOnModified","errorClass","errorElementClass","errorMessageClass","allowHtmlMessages","grouping","deep","live","validate","configuration","html5Attributes","html5InputTypes","reset","seedId","getTime","domData","domDataKey","isArray","o","Object","prototype","toString","call","isObject","isNumber","isObservableArray","instance","values","r","i","hasOwnProperty","push","getValue","hasAttribute","node","attr","getAttribute","element","setAttribute","isValidatable","rules","isModified","insertAfter","newNode","parentNode","insertBefore","nextSibling","newId","getConfigOptions","contextFor","setDomData","data","key","getDomData","nodeType","context","getOriginalElementTitle","savedOriginalTitle","currentTitle","title","hasSavedOriginalTitle","async","expr","window","setImmediate","setTimeout","object","callback","prop","api","cleanUpSubscriptions","subscriptions","subscription","dispose","flagged","obj","__kv_traversed","length","runTraversal","validatables","traverseGraph","level","objValues","peek","isObservable","errors","validatable","subscribe","graphMonitor","valueHasMutated","_destroy","collectErrors","array","isInitialized","init","force","configure","group","result","computed","showAllMessages","show","isAnyMessageShown","invalidAndModifiedPresent","arrayFirst","_updateState","newValue","Error","replacements","replace","index","addRule","addAnonymousRule","ruleObj","onlyIf","condition","addExtender","ruleName","extenders","insertValidationMessage","span","document","createElement","className","parseInputValidationAttributes","valueAccessor","currentType","writeInputValidationAttributes","contexts","read","RegExp","source","disposeWhenNodeIsRemoved","makeBindingHandlerValidatable","handlerName","bindingHandlers","allBindingsAccessor","viewModel","bindingContext","setRules","target","definition","ruleDefinitions","targetValue","unwrappedTargetValue","nonRules","required","testVal","String","trim","minLength","normalizedVal","maxLength","step","dif","Math","abs","test","phoneNumber","otherValue","c","collection","external","externalValue","counter","arrayFilter","item","config","validationMessageElement","renderTemplate","field","applyBindingsToNode","validationMessage","validationElement","textInput","update","obsv","isVisible","isCurrentlyVisible","style","display","setHtml","text","cssSettingsAccessor","css","shouldShow","hasModification","data-orig-title","newConfig","enable","validationOptions","throttleEvaluation","throttle","observableArray","previousError","previousIsValid","notifySubscribers","clearError","h_change","h_obsValidationTrigger","validateObservable","_disposeValidation","removeAll","getSubscriptionsCount","_subscriptions","ruleContexts","len","localize","msgTranslations","applyBindingsWithValidation","rootN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"file":"knockout.validation.min.js","sources":["knockout.validation.js"],"names":["factory","require","exports","module","define","ko","validation","minMaxValidatorFactory","validatorName","isMaxValidation","val","options","kv","utils","isEmptyVal","comparisonValue","type","undefined","typeAttr","value","isNaN","Date","regex","valMatches","comparisonValueMatches","toLowerCase","match","parseFloat","validateSync","observable","rule","ctx","validator","params","unwrap","setError","formatMessage","message","validateAsync","isValidating","callBack","valObj","isValid","msg","__valid__","error","koUtils","unwrapObservable","forEach","arrayForEach","extend","defaults","registerExtenders","messagesOnModified","errorsAsTitle","errorsAsTitleOnModified","messageTemplate","insertMessages","parseInputAttributes","writeInputAttributes","decorateInputElement","decorateElementOnModified","errorClass","errorElementClass","errorMessageClass","allowHtmlMessages","grouping","deep","live","validate","configuration","html5Attributes","html5InputTypes","reset","seedId","getTime","domData","domDataKey","isArray","o","Object","prototype","toString","call","isObject","isNumber","isObservableArray","instance","values","r","i","hasOwnProperty","push","getValue","hasAttribute","node","attr","getAttribute","element","setAttribute","isValidatable","rules","isModified","insertAfter","newNode","parentNode","insertBefore","nextSibling","newId","getConfigOptions","contextFor","setDomData","data","key","getDomData","nodeType","context","getOriginalElementTitle","savedOriginalTitle","currentTitle","title","hasSavedOriginalTitle","async","expr","window","setImmediate","setTimeout","object","callback","prop","api","cleanUpSubscriptions","subscriptions","subscription","dispose","flagged","obj","__kv_traversed","length","runTraversal","validatables","traverseGraph","level","objValues","peek","isObservable","errors","validatable","subscribe","graphMonitor","valueHasMutated","_destroy","collectErrors","array","isInitialized","init","force","configure","group","result","computed","showAllMessages","show","isAnyMessageShown","invalidAndModifiedPresent","arrayFirst","_updateState","newValue","Error","replacements","replace","index","addRule","hasRule","item","addAnonymousRule","ruleObj","onlyIf","condition","addExtender","ruleName","extenders","insertValidationMessage","span","document","createElement","className","parseInputValidationAttributes","valueAccessor","currentType","writeInputValidationAttributes","contexts","read","RegExp","source","disposeWhenNodeIsRemoved","makeBindingHandlerValidatable","handlerName","bindingHandlers","allBindingsAccessor","viewModel","bindingContext","setRules","target","definition","ruleDefinitions","targetValue","unwrappedTargetValue","nonRules","required","testVal","String","trim","minLength","normalizedVal","maxLength","step","dif","Math","abs","test","phoneNumber","otherValue","c","collection","external","externalValue","counter","arrayFilter","config","validationMessageElement","renderTemplate","field","applyBindingsToNode","validationMessage","validationElement","textInput","update","obsv","isVisible","isCurrentlyVisible","style","display","setHtml","text","cssSettingsAccessor","css","shouldShow","hasModification","data-orig-title","newConfig","enable","validationOptions","throttleEvaluation","throttle","observableArray","previousError","previousIsValid","notifySubscribers","clearError","h_change","h_obsValidationTrigger","validateObservable","_disposeValidation","removeAll","getSubscriptionsCount","_subscriptions","ruleContexts","len","localize","msgTranslations","applyBindingsWithValidation","rootNode","body","applyBindings","origApplyBindings","validatedObservable","initialValue"],"mappings":";;;;;;;;;CAUC,SAAUA,GAGgB,kBAAZC,UAA6C,gBAAZC,UAA0C,gBAAXC,QAEvEH,EAAQC,QAAQ,YAAaC,SACJ,kBAAXE,SAAyBA,OAAY,IAEnDA,QAAQ,WAAY,WAAYJ,GAGhCA,EAAQK,GAAIA,GAAGC,gBAErB,SAAWD,EAAIH,GAksBjB,QAASK,GAAuBC,GAC5B,GAAIC,GAAoC,QAAlBD,CAEtB,OAAO,UAAUE,EAAKC,GAClB,GAAIC,EAAGC,MAAMC,WAAWJ,GACpB,OAAO,CAGX,IAAIK,GAAiBC,CACIC,UAArBN,EAAQO,UAGRF,EAAO,OACPD,EAAkBJ,IAElBK,EAAOL,EAAQO,SACfH,EAAkBJ,EAAQQ,OAKzBC,MAAML,IAAsBA,YAA2BM,QACxDL,EAAO,SAGX,IAAIM,GAAOC,EAAYC,CACvB,QAAQR,EAAKS,eACT,IAAK,OAGD,GAFAH,EAAQ,qBACRC,EAAab,EAAIgB,MAAMJ,GACJ,OAAfC,EACA,KAAM,qBAAuBf,EAAgB,+HAKjD,OAFAgB,GAAyBT,EAAgBW,MAAMJ,GAE1CE,EAIDf,EACQc,EAAW,GAAKC,EAAuB,IAEzCD,E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AI2F,GAAOzO,EAAGwB,WAAWwP,EA6BzB,OA5BAvC,GAAK5F,OAAStI,EAAGkJ,MAAMlJ,EAAGC,MAAMuE,SAASiM,GAAgBA,KAAmB1Q,GAC5EmO,EAAKpM,QAAUrC,EAAGwB,WAAoC,IAAzBiN,EAAK5F,SAASR,QAEvCrI,EAAG4I,aAAa6F,EAAK5F,QACxB4F,EAAK5F,OAAOE,UAAU,SAASF,GAC9B4F,EAAKpM,QAA0B,IAAlBwG,EAAOR,UAIrBrI,EAAG2J,SAAS8E,EAAK5F,QAAQE,UAAU,SAAUF,GAC5C4F,EAAKpM,QAA0B,IAAlBwG,EAAOR,UAItBoG,EAAK1F,UAAU,SAASmB,GAClB3J,EAAGC,MAAMuE,SAASmF,KAMtBA,MAGDuE,EAAK5F,OAAOoB,aAAaC,GACzBuE,EAAKpM,QAAiC,IAAzBoM,EAAK5F,SAASR,UAGrBoG"} \ No newline at end of file diff --git a/Src/api.js b/Src/api.js index 6850fee0..9d781132 100644 --- a/Src/api.js +++ b/Src/api.js @@ -243,8 +243,14 @@ addRule: function (observable, rule) { observable.extend({ validatable: true }); - //push a Rule Context to the observables local array of Rule Contexts - observable.rules.push(rule); + var hasRule = !!ko.utils.arrayFirst(observable.rules(), function(item) { + return item.rule && item.rule === rule.rule; + }); + + if (!hasRule) { + //push a Rule Context to the observables local array of Rule Contexts + observable.rules.push(rule); + } return observable; }, diff --git a/Tests/api-tests.js b/Tests/api-tests.js index 6a519987..3b42252a 100644 --- a/Tests/api-tests.js +++ b/Tests/api-tests.js @@ -55,6 +55,27 @@ QUnit.test('clearError clears automatic errors', function(assert) { //#endregion +//region API Tests + +QUnit.module('API Tests'); + +QUnit.test('Issue #277 - addRule should ignore rule if already defined', function(assert) { + + var testObj = ko.observable(1).extend({validatable: true}); + + testObj.extend({min: 10}); + assert.equal(testObj.rules().length, 1, 'rule is added'); + assert.equal(testObj.error(), 'Please enter a value greater than or equal to 10.'); + + testObj.extend({min: 20}); + ko.validation.validateObservable(testObj); + + assert.equal(testObj.rules().length, 1, 'rule is not added'); + assert.equal(testObj.error(), 'Please enter a value greater than or equal to 10.'); +}); + +//endregion + //#region Grouping Tests QUnit.module('Grouping Tests'); diff --git a/Tests/validation-ui-tests.js b/Tests/validation-ui-tests.js index 17c8d6d5..c466bfdf 100644 --- a/Tests/validation-ui-tests.js +++ b/Tests/validation-ui-tests.js @@ -123,6 +123,46 @@ QUnit.test('selectedOptions Binding Works', function(assert) { assert.equal(msg, 'Please select at least one item.', msg); }); +QUnit.test('Issue #277 - parseInputAttributes does not duplicate rules when parseInputAttributes=true', function(assert) { + var done = assert.async(); + + ko.validation.init({parseInputAttributes: true, writeInputAttributes: false}, true); + + var testObj = ko.observable('').extend({required: true, email: true}); + addTestHtml(''); + applyTestBindings({ email: testObj }); + + setTimeout(function() { + assert.equal(testObj.rules().length, 2, 'rules are not duplicated'); + assert.equal(testObj.error(), 'This field is required.'); + + testObj('abc'); + assert.equal(testObj.error(), 'Please enter a proper email address.'); + + done(); + }, 1); +}); + +QUnit.test('Issue #277 - parseInputAttributes does not duplicate rules when parseInputAttributes=true', function(assert) { + var done = assert.async(); + + ko.validation.init({parseInputAttributes: true, writeInputAttributes: true}, true); + + var testObj = ko.observable('').extend({required: true, email: true}); + addTestHtml(''); + applyTestBindings({ email: testObj }); + + setTimeout(function() { + assert.equal(testObj.rules().length, 2, 'rules are not duplicated'); + assert.equal(testObj.error(), 'This field is required.'); + + testObj('abc'); + assert.equal(testObj.error(), 'Please enter a proper email address.'); + + done(); + }, 1); +}); + //#region Inserting Messages QUnit.test('Inserting Messages Works', function(assert) { From 4d308b017d2a0fa17e7bf84fa136b9e7d6067e5e Mon Sep 17 00:00:00 2001 From: Brett Morien Date: Thu, 8 Jan 2015 11:29:49 -0800 Subject: [PATCH 120/165] Add basic collection methods to errors, exposing raw validatables. Closes #449 --- Dist/knockout.validation.js | 41 +++++++++--- Dist/knockout.validation.min.js | 2 +- Dist/knockout.validation.min.js.map | 2 +- Src/api.js | 41 +++++++++--- Tests/api-tests.js | 100 ++++++++++++++++++++++++++++ 5 files changed, 168 insertions(+), 18 deletions(-) diff --git a/Dist/knockout.validation.js b/Dist/knockout.validation.js index d526e41c..0bda9f78 100644 --- a/Dist/knockout.validation.js +++ b/Dist/knockout.validation.js @@ -365,10 +365,7 @@ kv.configuration = configuration; show = true; } - // ensure we have latest changes - result(); - - forEach(context.validatables, function (observable) { + result.forEach(function (observable) { if (utils.isValidatable(observable)) { observable.isModified(show); } @@ -378,15 +375,43 @@ kv.configuration = configuration; result.isAnyMessageShown = function () { var invalidAndModifiedPresent; - // ensure we have latest changes - result(); - - invalidAndModifiedPresent = !!koUtils.arrayFirst(context.validatables, function (observable) { + invalidAndModifiedPresent = !!result.find(function (observable) { return utils.isValidatable(observable) && !observable.isValid() && observable.isModified(); }); return invalidAndModifiedPresent; }; + result.filter = function(predicate) { + predicate = predicate || function () { return true; }; + // ensure we have latest changes + result(); + + return koUtils.arrayFilter(context.validatables, predicate); + }; + + result.find = function(predicate) { + predicate = predicate || function () { return true; }; + // ensure we have latest changes + result(); + + return koUtils.arrayFirst(context.validatables, predicate); + }; + + result.forEach = function(callback) { + callback = callback || function () { }; + // ensure we have latest changes + result(); + + forEach(context.validatables, callback); + }; + + result.map = function(mapping) { + mapping = mapping || function (item) { return item; }; + // ensure we have latest changes + result(); + + return koUtils.arrayMap(context.validatables, mapping); + }; /** * @private You should not rely on this method being here. diff --git a/Dist/knockout.validation.min.js b/Dist/knockout.validation.min.js index 90b57e09..2685ae98 100644 --- a/Dist/knockout.validation.min.js +++ b/Dist/knockout.validation.min.js @@ -7,5 +7,5 @@ =============================================================================== */ -!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||e instanceof Date||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for week input. Should look like '2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for month input. Should look like '2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:h(c.params))?!0:(a.setError(f.formatMessage(c.message||b.message,h(c.params),a)),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,h(c.params),a)),a.__valid__(e)),void a.isValidating(!1)):void a.isValidating(!1)};b.validator(a(),h(c.params||!0),d)}if("undefined"==typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0,live:!1},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},isNumber:function(a){return!isNaN(a)},isObservableArray:function(a){return!!a&&"function"==typeof a.remove&&"function"==typeof a.removeAll&&"function"==typeof a.destroy&&"function"==typeof a.destroyAll&&"function"==typeof a.indexOf&&"function"==typeof a.replace},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return!!(a&&a.rules&&a.isValid&&a.isModified)},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},forEach:function(a,b){if(f.utils.isArray(a))return i(a,b);for(var c in a)a.hasOwnProperty(c)&&b(a[c],c)}}}();var m=function(){function b(a){i(a.subscriptions,function(a){a.dispose()}),a.subscriptions=[]}function c(a){a.options.deep&&(i(a.flagged,function(a){delete a.__kv_traversed}),a.flagged.length=0),a.options.live||b(a)}function d(a,d){d.validatables=[],b(d),e(a,d),c(d)}function e(b,c,d){var f=[],g=b.peek?b.peek():b;b.__kv_traversed!==!0&&(c.options.deep&&(b.__kv_traversed=!0,c.flagged.push(b)),d=void 0!==d?d:c.options.deep?1:-1,a.isObservable(b)&&(b.errors||n.isValidatable(b)||b.extend({validatable:!0}),c.validatables.push(b),c.options.live&&n.isObservableArray(b)&&c.subscriptions.push(b.subscribe(function(){c.graphMonitor.valueHasMutated()}))),g&&!g._destroy&&(n.isArray(g)?f=g:n.isObject(g)&&(f=n.values(g))),0!==d&&n.forEach(f,function(a){a&&!a.nodeType&&e(a,c,d+1)}))}function k(a){var b=[];return i(a,function(a){n.isValidatable(a)&&!a.isValid()&&b.push(a.error.peek())}),b}var l=0,m=f.configuration,n=f.utils;return{init:function(a,b){l>0&&!b||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||m.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||m.errorMessageClass,j(m,a),m.registerExtenders&&f.registerExtenders(),l=1)},configure:function(a){f.init(a)},reset:f.configuration.reset,group:function(b,c){c=j(j({},m.grouping),c);var e={options:c,graphMonitor:a.observable(),flagged:[],subscriptions:[],validatables:[]},f=null;return f=c.observable?a.computed(function(){return e.graphMonitor(),d(b,e),k(e.validatables)}):function(){return d(b,e),k(e.validatables)},f.showAllMessages=function(a){void 0===a&&(a=!0),f(),i(e.validatables,function(b){n.isValidatable(b)&&b.isModified(a)})},f.isAnyMessageShown=function(){var a;return f(),a=!!g.arrayFirst(e.validatables,function(a){return n.isValidatable(a)&&!a.isValid()&&a.isModified()})},f._updateState=function(a){if(!n.isObject(a))throw new Error("An object is required.");return b=a,c.observable?void e.graphMonitor.valueHasMutated():(d(a,e),k(e.validatables))},f},formatMessage:function(a,b,c){if(n.isObject(b)&&b.typeAttr&&(b=b.value),"function"==typeof a)return a(b,c);var d=h(b)||[];return n.isArray(d)||(d=[d]),a.replace(/{(\d+)}/gi,function(a,b){return"undefined"!=typeof d[b]?d[b]:a})},addRule:function(a,b){a.extend({validatable:!0});var c=!!g.arrayFirst(a.rules(),function(a){return a.rule&&a.rule===b.rule});return c||a.rules.push(b),a},addAnonymousRule:function(a,b){void 0===b.message&&(b.message="Error"),b.onlyIf&&(b.condition=b.onlyIf),f.addRule(a,b)},addExtender:function(b){a.extenders[b]=function(a,c){return c&&(c.message||c.onlyIf)?f.addRule(a,{rule:b,message:c.message,params:n.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(m.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=n.getConfigOptions(a).errorMessageClass,n.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(n.hasAttribute(a,c)){var d=a.getAttribute(c)||!0;if("min"===c||"max"===c){var e=a.getAttribute("type");"undefined"!=typeof e&&e||(e="text"),d={typeAttr:e,value:d}}f.addRule(b(),{rule:c,params:d})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(b,c){var d=c();if(d&&d.rules){var e=d.rules();i(f.configuration.html5Attributes,function(c){var d=g.arrayFirst(e,function(a){return a.rule&&a.rule.toLowerCase()===c.toLowerCase()});d&&a.computed({read:function(){var e=a.unwrap(d.params);"pattern"===d.rule&&e instanceof RegExp&&(e=e.source),b.setAttribute(c,e)},disposeWhenNodeIsRemoved:b})}),e=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var d=function(b,c){if(b&&c)for(var e in c)if(c.hasOwnProperty(e)){var g=c[e];if(b[e]){var i=b[e],j=h(i),k={},l={};for(var m in g)g.hasOwnProperty(m)&&(f.rules[m]?k[m]=g[m]:l[m]=g[m]);if(a.isObservable(i)&&i.extend(k),j&&n.isArray(j))for(var o=0;o0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}."},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address."},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date."},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[-/](?:0?[1-9]|1[012])[-/](?:0?[1-9]|[12][0-9]|3[01])$/.test(a):!0},message:"Please enter a proper date."},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number."},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit."},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number."},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal."},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(c,function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateInputElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.textInput&&f.makeBindingHandlerValidatable("textInput"),f.makeBindingHandlerValidatable("selectedOptions"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),i=(h(d),!1),j=!1;if(null===d||"undefined"==typeof d)throw new Error("Cannot bind validationMessage to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");i=d.isModified(),j=d.isValid();var k=null;(!e.messagesOnModified||i)&&(k=j?null:d.error);var l=!e.messagesOnModified||i?!j:!1,m="none"!==b.style.display;e.allowHtmlMessages?g.setHtml(b,k):a.bindingHandlers.text.update(b,function(){return k}),m&&!l?b.style.display="none":!m&&l&&(b.style.display="")}},a.bindingHandlers.validationElement={update:function(b,c,d){var e=c(),g=f.utils.getConfigOptions(b),i=(h(e),!1),j=!1;if(null===e||"undefined"==typeof e)throw new Error("Cannot bind validationElement to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!e.isValid||!e.isModified)throw new Error("Observable is not validatable");i=e.isModified(),j=e.isValid();var k=function(){var a={},b=!g.decorateElementOnModified||i?!j:!1;return a[g.errorElementClass]=b,a};a.bindingHandlers.css.update(b,k,d),g.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!g.errorsAsTitleOnModified||i,c=f.utils.getOriginalElementTitle(b);return a&&!j?{title:e.error,"data-orig-title":c}:!a||j?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){var c=b.error.peek(),d=b.__valid__.peek();b.error(a),b.__valid__(!1),c===a||d||b.isValid.notifySubscribers()},b.clearError=function(){return b.error(null),b.__valid__(!0),b};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){b(),b.rules();return f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified.getSubscriptionsCount()>0&&(b.isModified._subscriptions.change=[]),b.isValidating.getSubscriptionsCount()>0&&(b.isValidating._subscriptions.change=[]),b.__valid__.getSubscriptionsCount()>0&&(b.__valid__._subscriptions.change=[]),g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=c.rule?f.rules[c.rule]:c,b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0},f.localize=function(a){var b;for(b in a)f.rules.hasOwnProperty(b)&&(f.rules[b].message=a[b])},a.applyBindingsWithValidation=function(b,c,d){var e,g=document.body;c&&c.nodeType?(g=c,e=d):e=c,f.init(),e&&(e=j(j({},f.configuration),e),f.utils.setDomData(g,e)),a.applyBindings(b,g)};var n=a.applyBindings;a.applyBindings=function(a,b){f.init(),n(a,b)},a.validatedObservable=function(b,c){if(!c&&!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var d=a.observable(b);return d.errors=f.group(f.utils.isObject(b)?b:{},c),d.isValid=a.observable(0===d.errors().length),a.isObservable(d.errors)?d.errors.subscribe(function(a){d.isValid(0===a.length)}):a.computed(d.errors).subscribe(function(a){d.isValid(0===a.length)}),d.subscribe(function(a){f.utils.isObject(a)||(a={}),d.errors._updateState(a),d.isValid(0===d.errors().length)}),d}}); +!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||e instanceof Date||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for week input. Should look like '2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for month input. Should look like '2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:h(c.params))?!0:(a.setError(f.formatMessage(c.message||b.message,h(c.params),a)),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,h(c.params),a)),a.__valid__(e)),void a.isValidating(!1)):void a.isValidating(!1)};b.validator(a(),h(c.params||!0),d)}if("undefined"==typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0,live:!1},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},isNumber:function(a){return!isNaN(a)},isObservableArray:function(a){return!!a&&"function"==typeof a.remove&&"function"==typeof a.removeAll&&"function"==typeof a.destroy&&"function"==typeof a.destroyAll&&"function"==typeof a.indexOf&&"function"==typeof a.replace},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return!!(a&&a.rules&&a.isValid&&a.isModified)},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},forEach:function(a,b){if(f.utils.isArray(a))return i(a,b);for(var c in a)a.hasOwnProperty(c)&&b(a[c],c)}}}();var m=function(){function b(a){i(a.subscriptions,function(a){a.dispose()}),a.subscriptions=[]}function c(a){a.options.deep&&(i(a.flagged,function(a){delete a.__kv_traversed}),a.flagged.length=0),a.options.live||b(a)}function d(a,d){d.validatables=[],b(d),e(a,d),c(d)}function e(b,c,d){var f=[],g=b.peek?b.peek():b;b.__kv_traversed!==!0&&(c.options.deep&&(b.__kv_traversed=!0,c.flagged.push(b)),d=void 0!==d?d:c.options.deep?1:-1,a.isObservable(b)&&(b.errors||n.isValidatable(b)||b.extend({validatable:!0}),c.validatables.push(b),c.options.live&&n.isObservableArray(b)&&c.subscriptions.push(b.subscribe(function(){c.graphMonitor.valueHasMutated()}))),g&&!g._destroy&&(n.isArray(g)?f=g:n.isObject(g)&&(f=n.values(g))),0!==d&&n.forEach(f,function(a){a&&!a.nodeType&&e(a,c,d+1)}))}function k(a){var b=[];return i(a,function(a){n.isValidatable(a)&&!a.isValid()&&b.push(a.error.peek())}),b}var l=0,m=f.configuration,n=f.utils;return{init:function(a,b){l>0&&!b||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||m.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||m.errorMessageClass,j(m,a),m.registerExtenders&&f.registerExtenders(),l=1)},configure:function(a){f.init(a)},reset:f.configuration.reset,group:function(b,c){c=j(j({},m.grouping),c);var e={options:c,graphMonitor:a.observable(),flagged:[],subscriptions:[],validatables:[]},f=null;return f=c.observable?a.computed(function(){return e.graphMonitor(),d(b,e),k(e.validatables)}):function(){return d(b,e),k(e.validatables)},f.showAllMessages=function(a){void 0===a&&(a=!0),f.forEach(function(b){n.isValidatable(b)&&b.isModified(a)})},f.isAnyMessageShown=function(){var a;return a=!!f.find(function(a){return n.isValidatable(a)&&!a.isValid()&&a.isModified()})},f.filter=function(a){return a=a||function(){return!0},f(),g.arrayFilter(e.validatables,a)},f.find=function(a){return a=a||function(){return!0},f(),g.arrayFirst(e.validatables,a)},f.forEach=function(a){a=a||function(){},f(),i(e.validatables,a)},f.map=function(a){return a=a||function(a){return a},f(),g.arrayMap(e.validatables,a)},f._updateState=function(a){if(!n.isObject(a))throw new Error("An object is required.");return b=a,c.observable?void e.graphMonitor.valueHasMutated():(d(a,e),k(e.validatables))},f},formatMessage:function(a,b,c){if(n.isObject(b)&&b.typeAttr&&(b=b.value),"function"==typeof a)return a(b,c);var d=h(b)||[];return n.isArray(d)||(d=[d]),a.replace(/{(\d+)}/gi,function(a,b){return"undefined"!=typeof d[b]?d[b]:a})},addRule:function(a,b){a.extend({validatable:!0});var c=!!g.arrayFirst(a.rules(),function(a){return a.rule&&a.rule===b.rule});return c||a.rules.push(b),a},addAnonymousRule:function(a,b){void 0===b.message&&(b.message="Error"),b.onlyIf&&(b.condition=b.onlyIf),f.addRule(a,b)},addExtender:function(b){a.extenders[b]=function(a,c){return c&&(c.message||c.onlyIf)?f.addRule(a,{rule:b,message:c.message,params:n.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(m.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=n.getConfigOptions(a).errorMessageClass,n.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(n.hasAttribute(a,c)){var d=a.getAttribute(c)||!0;if("min"===c||"max"===c){var e=a.getAttribute("type");"undefined"!=typeof e&&e||(e="text"),d={typeAttr:e,value:d}}f.addRule(b(),{rule:c,params:d})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(b,c){var d=c();if(d&&d.rules){var e=d.rules();i(f.configuration.html5Attributes,function(c){var d=g.arrayFirst(e,function(a){return a.rule&&a.rule.toLowerCase()===c.toLowerCase()});d&&a.computed({read:function(){var e=a.unwrap(d.params);"pattern"===d.rule&&e instanceof RegExp&&(e=e.source),b.setAttribute(c,e)},disposeWhenNodeIsRemoved:b})}),e=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var d=function(b,c){if(b&&c)for(var e in c)if(c.hasOwnProperty(e)){var g=c[e];if(b[e]){var i=b[e],j=h(i),k={},l={};for(var m in g)g.hasOwnProperty(m)&&(f.rules[m]?k[m]=g[m]:l[m]=g[m]);if(a.isObservable(i)&&i.extend(k),j&&n.isArray(j))for(var o=0;o0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}."},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address."},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date."},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[-/](?:0?[1-9]|1[012])[-/](?:0?[1-9]|[12][0-9]|3[01])$/.test(a):!0},message:"Please enter a proper date."},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number."},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit."},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number."},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal."},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(c,function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateInputElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.textInput&&f.makeBindingHandlerValidatable("textInput"),f.makeBindingHandlerValidatable("selectedOptions"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),i=(h(d),!1),j=!1;if(null===d||"undefined"==typeof d)throw new Error("Cannot bind validationMessage to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");i=d.isModified(),j=d.isValid();var k=null;(!e.messagesOnModified||i)&&(k=j?null:d.error);var l=!e.messagesOnModified||i?!j:!1,m="none"!==b.style.display;e.allowHtmlMessages?g.setHtml(b,k):a.bindingHandlers.text.update(b,function(){return k}),m&&!l?b.style.display="none":!m&&l&&(b.style.display="")}},a.bindingHandlers.validationElement={update:function(b,c,d){var e=c(),g=f.utils.getConfigOptions(b),i=(h(e),!1),j=!1;if(null===e||"undefined"==typeof e)throw new Error("Cannot bind validationElement to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!e.isValid||!e.isModified)throw new Error("Observable is not validatable");i=e.isModified(),j=e.isValid();var k=function(){var a={},b=!g.decorateElementOnModified||i?!j:!1;return a[g.errorElementClass]=b,a};a.bindingHandlers.css.update(b,k,d),g.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!g.errorsAsTitleOnModified||i,c=f.utils.getOriginalElementTitle(b);return a&&!j?{title:e.error,"data-orig-title":c}:!a||j?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){var c=b.error.peek(),d=b.__valid__.peek();b.error(a),b.__valid__(!1),c===a||d||b.isValid.notifySubscribers()},b.clearError=function(){return b.error(null),b.__valid__(!0),b};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){b(),b.rules();return f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified.getSubscriptionsCount()>0&&(b.isModified._subscriptions.change=[]),b.isValidating.getSubscriptionsCount()>0&&(b.isValidating._subscriptions.change=[]),b.__valid__.getSubscriptionsCount()>0&&(b.__valid__._subscriptions.change=[]),g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=c.rule?f.rules[c.rule]:c,b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0},f.localize=function(a){var b;for(b in a)f.rules.hasOwnProperty(b)&&(f.rules[b].message=a[b])},a.applyBindingsWithValidation=function(b,c,d){var e,g=document.body;c&&c.nodeType?(g=c,e=d):e=c,f.init(),e&&(e=j(j({},f.configuration),e),f.utils.setDomData(g,e)),a.applyBindings(b,g)};var n=a.applyBindings;a.applyBindings=function(a,b){f.init(),n(a,b)},a.validatedObservable=function(b,c){if(!c&&!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var d=a.observable(b);return d.errors=f.group(f.utils.isObject(b)?b:{},c),d.isValid=a.observable(0===d.errors().length),a.isObservable(d.errors)?d.errors.subscribe(function(a){d.isValid(0===a.length)}):a.computed(d.errors).subscribe(function(a){d.isValid(0===a.length)}),d.subscribe(function(a){f.utils.isObject(a)||(a={}),d.errors._updateState(a),d.isValid(0===d.errors().length)}),d}}); //# sourceMappingURL=knockout.validation.min.js.map \ No newline at end of file diff --git a/Dist/knockout.validation.min.js.map b/Dist/knockout.validation.min.js.map index c382b16c..a09c842c 100644 --- a/Dist/knockout.validation.min.js.map +++ b/Dist/knockout.validation.min.js.map @@ -1 +1 @@ -{"version":3,"file":"knockout.validation.min.js","sources":["knockout.validation.js"],"names":["factory","require","exports","module","define","ko","validation","minMaxValidatorFactory","validatorName","isMaxValidation","val","options","kv","utils","isEmptyVal","comparisonValue","type","undefined","typeAttr","value","isNaN","Date","regex","valMatches","comparisonValueMatches","toLowerCase","match","parseFloat","validateSync","observable","rule","ctx","validator","params","unwrap","setError","formatMessage","message","validateAsync","isValidating","callBack","valObj","isValid","msg","__valid__","error","koUtils","unwrapObservable","forEach","arrayForEach","extend","defaults","registerExtenders","messagesOnModified","errorsAsTitle","errorsAsTitleOnModified","messageTemplate","insertMessages","parseInputAttributes","writeInputAttributes","decorateInputElement","decorateElementOnModified","errorClass","errorElementClass","errorMessageClass","allowHtmlMessages","grouping","deep","live","validate","configuration","html5Attributes","html5InputTypes","reset","seedId","getTime","domData","domDataKey","isArray","o","Object","prototype","toString","call","isObject","isNumber","isObservableArray","instance","values","r","i","hasOwnProperty","push","getValue","hasAttribute","node","attr","getAttribute","element","setAttribute","isValidatable","rules","isModified","insertAfter","newNode","parentNode","insertBefore","nextSibling","newId","getConfigOptions","contextFor","setDomData","data","key","getDomData","nodeType","context","getOriginalElementTitle","savedOriginalTitle","currentTitle","title","hasSavedOriginalTitle","async","expr","window","setImmediate","setTimeout","object","callback","prop","api","cleanUpSubscriptions","subscriptions","subscription","dispose","flagged","obj","__kv_traversed","length","runTraversal","validatables","traverseGraph","level","objValues","peek","isObservable","errors","validatable","subscribe","graphMonitor","valueHasMutated","_destroy","collectErrors","array","isInitialized","init","force","configure","group","result","computed","showAllMessages","show","isAnyMessageShown","invalidAndModifiedPresent","arrayFirst","_updateState","newValue","Error","replacements","replace","index","addRule","hasRule","item","addAnonymousRule","ruleObj","onlyIf","condition","addExtender","ruleName","extenders","insertValidationMessage","span","document","createElement","className","parseInputValidationAttributes","valueAccessor","currentType","writeInputValidationAttributes","contexts","read","RegExp","source","disposeWhenNodeIsRemoved","makeBindingHandlerValidatable","handlerName","bindingHandlers","allBindingsAccessor","viewModel","bindingContext","setRules","target","definition","ruleDefinitions","targetValue","unwrappedTargetValue","nonRules","required","testVal","String","trim","minLength","normalizedVal","maxLength","step","dif","Math","abs","test","phoneNumber","otherValue","c","collection","external","externalValue","counter","arrayFilter","config","validationMessageElement","renderTemplate","field","applyBindingsToNode","validationMessage","validationElement","textInput","update","obsv","isVisible","isCurrentlyVisible","style","display","setHtml","text","cssSettingsAccessor","css","shouldShow","hasModification","data-orig-title","newConfig","enable","validationOptions","throttleEvaluation","throttle","observableArray","previousError","previousIsValid","notifySubscribers","clearError","h_change","h_obsValidationTrigger","validateObservable","_disposeValidation","removeAll","getSubscriptionsCount","_subscriptions","ruleContexts","len","localize","msgTranslations","applyBindingsWithValidation","rootNode","body","applyBindings","origApplyBindings","validatedObservable","initialValue"],"mappings":";;;;;;;;;CAUC,SAAUA,GAGgB,kBAAZC,UAA6C,gBAAZC,UAA0C,gBAAXC,QAEvEH,EAAQC,QAAQ,YAAaC,SACJ,kBAAXE,SAAyBA,OAAY,IAEnDA,QAAQ,WAAY,WAAYJ,GAGhCA,EAAQK,GAAIA,GAAGC,gBAErB,SAAWD,EAAIH,GAksBjB,QAASK,GAAuBC,GAC5B,GAAIC,GAAoC,QAAlBD,CAEtB,OAAO,UAAUE,EAAKC,GAClB,GAAIC,EAAGC,MAAMC,WAAWJ,GACpB,OAAO,CAGX,IAAIK,GAAiBC,CACIC,UAArBN,EAAQO,UAGRF,EAAO,OACPD,EAAkBJ,IAElBK,EAAOL,EAAQO,SACfH,EAAkBJ,EAAQQ,OAKzBC,MAAML,IAAsBA,YAA2BM,QACxDL,EAAO,SAG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AC3B7Q,GAAG6Q,cAAgB,SAAU1E,EAAWwE,GAEvCpQ,EAAG+I,OAEHwH,EAAkB3E,EAAWwE,IAG9B3Q,EAAG+Q,oBAAsB,SAAUC,EAAc1Q,GAChD,IAAKA,IAAYC,EAAGC,MAAMuE,SAASiM,GAClC,MAAOhR,GAAGwB,WAAWwP,GAAcnO,QAASiG,aAAa,GAG1D,IAAI2F,GAAOzO,EAAGwB,WAAWwP,EA6BzB,OA5BAvC,GAAK5F,OAAStI,EAAGkJ,MAAMlJ,EAAGC,MAAMuE,SAASiM,GAAgBA,KAAmB1Q,GAC5EmO,EAAKpM,QAAUrC,EAAGwB,WAAoC,IAAzBiN,EAAK5F,SAASR,QAEvCrI,EAAG4I,aAAa6F,EAAK5F,QACxB4F,EAAK5F,OAAOE,UAAU,SAASF,GAC9B4F,EAAKpM,QAA0B,IAAlBwG,EAAOR,UAIrBrI,EAAG2J,SAAS8E,EAAK5F,QAAQE,UAAU,SAAUF,GAC5C4F,EAAKpM,QAA0B,IAAlBwG,EAAOR,UAItBoG,EAAK1F,UAAU,SAASmB,GAClB3J,EAAGC,MAAMuE,SAASmF,KAMtBA,MAGDuE,EAAK5F,OAAOoB,aAAaC,GACzBuE,EAAKpM,QAAiC,IAAzBoM,EAAK5F,SAASR,UAGrBoG"} \ No newline at end of file +{"version":3,"file":"knockout.validation.min.js","sources":["knockout.validation.js"],"names":["factory","require","exports","module","define","ko","validation","minMaxValidatorFactory","validatorName","isMaxValidation","val","options","kv","utils","isEmptyVal","comparisonValue","type","undefined","typeAttr","value","isNaN","Date","regex","valMatches","comparisonValueMatches","toLowerCase","match","parseFloat","validateSync","observable","rule","ctx","validator","params","unwrap","setError","formatMessage","message","validateAsync","isValidating","callBack","valObj","isValid","msg","__valid__","error","koUtils","unwrapObservable","forEach","arrayForEach","extend","defaults","registerExtenders","messagesOnModified","errorsAsTitle","errorsAsTitleOnModified","messageTemplate","insertMessages","parseInputAttributes","writeInputAttributes","decorateInputElement","decorateElementOnModified","errorClass","errorElementClass","errorMessageClass","allowHtmlMessages","grouping","deep","live","validate","configuration","html5Attributes","html5InputTypes","reset","seedId","getTime","domData","domDataKey","isArray","o","Object","prototype","toString","call","isObject","isNumber","isObservableArray","instance","values","r","i","hasOwnProperty","push","getValue","hasAttribute","node","attr","getAttribute","element","setAttribute","isValidatable","rules","isModified","insertAfter","newNode","parentNode","insertBefore","nextSibling","newId","getConfigOptions","contextFor","setDomData","data","key","getDomData","nodeType","context","getOriginalElementTitle","savedOriginalTitle","currentTitle","title","hasSavedOriginalTitle","async","expr","window","setImmediate","setTimeout","object","callback","prop","api","cleanUpSubscriptions","subscriptions","subscription","dispose","flagged","obj","__kv_traversed","length","runTraversal","validatables","traverseGraph","level","objValues","peek","isObservable","errors","validatable","subscribe","graphMonitor","valueHasMutated","_destroy","collectErrors","array","isInitialized","init","force","configure","group","result","computed","showAllMessages","show","isAnyMessageShown","invalidAndModifiedPresent","find","filter","predicate","arrayFilter","arrayFirst","map","mapping","item","arrayMap","_updateState","newValue","Error","replacements","replace","index","addRule","hasRule","addAnonymousRule","ruleObj","onlyIf","condition","addExtender","ruleName","extenders","insertValidationMessage","span","document","createElement","className","parseInputValidationAttributes","valueAccessor","currentType","writeInputValidationAttributes","contexts","read","RegExp","source","disposeWhenNodeIsRemoved","makeBindingHandlerValidatable","handlerName","bindingHandlers","allBindingsAccessor","viewModel","bindingContext","setRules","target","definition","ruleDefinitions","targetValue","unwrappedTargetValue","nonRules","required","testVal","String","trim","minLength","normalizedVal","maxLength","step","dif","Math","abs","test","phoneNumber","otherValue","c","collection","external","externalValue","counter","config","validationMessageElement","renderTemplate","field","applyBindingsToNode","validationMessage","validationElement","textInput","update","obsv","isVisible","isCurrentlyVisible","style","display","setHtml","text","cssSettingsAccessor","css","shouldShow","hasModification","data-orig-title","newConfig","enable","validationOptions","throttleEvaluation","throttle","observableArray","previousError","previousIsValid","notifySubscribers","clearError","h_change","h_obsValidationTrigger","validateObservable","_disposeValidation","removeAll","getSubscriptionsCount","_subscriptions","ruleContexts","len","localize","msgTranslations","applyBindingsWithValidation","rootNode","body","applyBindings","origApplyBindings","validatedObservable","initialValue"],"mappings":";;;;;;;;;CAUC,SAAUA,GAGgB,kBAAZC,UAA6C,gBAAZC,UAA0C,gBAAXC,QAEvEH,EAAQC,QAAQ,YAAaC,SACJ,kBAAXE,SAAyBA,OAAY,IAEnDA,QAAQ,WAAY,WAAYJ,GAGhCA,EAAQK,GAAIA,GAAGC,gBAErB,SAAWD,EAAIH,GA2tBjB,QAASK,GAAuBC,GAC5B,GAAIC,GAAoC,QAAlBD,CAEtB,OAAO,UAAUE,EAAKC,GAClB,GAAIC,EAAGC,MAAMC,WAAWJ,GACpB,OAAO,CAGX,IAAIK,GAAiBC,CACIC,UAArBN,EAAQO,UAGRF,EAAO,OACPD,EAAkBJ,IAElBK,EAAOL,EAAQO,SACfH,EAAkBJ,EAAQQ,OAKzBC,MAAML,IAAsBA,YAA2BM,QACxDL,EAAO,SAGX,IAAIM,GAAOC,EAAYC,CACvB,QAAQR,EAAKS,eACT,IAAK,OAGD,GAFAH,EAAQ,qBACRC,EAAab,EAAIgB,MAAMJ,GACJ,OAAfC,EACA,KAAM,qBAAuBf,EAAgB,+HAKjD,OAFAgB,GAAyBT,EAAgBW,MAAMJ,GAE1CE,EAIDf,EACQc,EAAW,GAAKC,EAAuB,IAEzCD,EAAW,KAAOC,EAAuB,IAAQD,EAAW,IAAMC,EAAuB,GAEvFD,EAAW,GAAKC,EAAuB,IAEzCD,EAAW,KAAOC,EAAuB,IAAQD,EAAW,IAAMC,EAAuB,IAVxF,CAcf,KAAK,QAGD,GAFAF,EAAQ,oBACRC,EAAab,EAAIgB,MAAMJ,GACJ,OAAfC,EACA,KAAM,qBAAuBf,EAAgB,iIAKjD,OAFAgB,GAAyBT,EAAgBW,MAAMJ,GAE1CE,EAIDf,EACSc,EAAW,GAAKC,EAAuB,IAE1CD,EAAW,KAAOC,EAAuB,IAAQD,EAAW,IAAMC,EAAu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IAAIiG,GAAO/O,EAAGwB,WAAW8P,EA6BzB,OA5BAvC,GAAKlG,OAAStI,EAAGkJ,MAAMlJ,EAAGC,MAAMuE,SAASuM,GAAgBA,KAAmBhR,GAC5EyO,EAAK1M,QAAUrC,EAAGwB,WAAoC,IAAzBuN,EAAKlG,SAASR,QAEvCrI,EAAG4I,aAAamG,EAAKlG,QACxBkG,EAAKlG,OAAOE,UAAU,SAASF,GAC9BkG,EAAK1M,QAA0B,IAAlBwG,EAAOR,UAIrBrI,EAAG2J,SAASoF,EAAKlG,QAAQE,UAAU,SAAUF,GAC5CkG,EAAK1M,QAA0B,IAAlBwG,EAAOR,UAItB0G,EAAKhG,UAAU,SAAS2B,GAClBnK,EAAGC,MAAMuE,SAAS2F,KAMtBA,MAGDqE,EAAKlG,OAAO4B,aAAaC,GACzBqE,EAAK1M,QAAiC,IAAzB0M,EAAKlG,SAASR,UAGrB0G"} \ No newline at end of file diff --git a/Src/api.js b/Src/api.js index 9d781132..6f134eff 100644 --- a/Src/api.js +++ b/Src/api.js @@ -169,10 +169,7 @@ show = true; } - // ensure we have latest changes - result(); - - ko.utils.arrayForEach(context.validatables, function (observable) { + result.forEach(function (observable) { if (utils.isValidatable(observable)) { observable.isModified(show); } @@ -182,15 +179,43 @@ result.isAnyMessageShown = function () { var invalidAndModifiedPresent; - // ensure we have latest changes - result(); - - invalidAndModifiedPresent = !!ko.utils.arrayFirst(context.validatables, function (observable) { + invalidAndModifiedPresent = !!result.find(function (observable) { return utils.isValidatable(observable) && !observable.isValid() && observable.isModified(); }); return invalidAndModifiedPresent; }; + result.filter = function(predicate) { + predicate = predicate || function () { return true; }; + // ensure we have latest changes + result(); + + return ko.utils.arrayFilter(context.validatables, predicate); + }; + + result.find = function(predicate) { + predicate = predicate || function () { return true; }; + // ensure we have latest changes + result(); + + return ko.utils.arrayFirst(context.validatables, predicate); + }; + + result.forEach = function(callback) { + callback = callback || function () { }; + // ensure we have latest changes + result(); + + ko.utils.arrayForEach(context.validatables, callback); + }; + + result.map = function(mapping) { + mapping = mapping || function (item) { return item; }; + // ensure we have latest changes + result(); + + return ko.utils.arrayMap(context.validatables, mapping); + }; /** * @private You should not rely on this method being here. diff --git a/Tests/api-tests.js b/Tests/api-tests.js index 3b42252a..400b0fe3 100644 --- a/Tests/api-tests.js +++ b/Tests/api-tests.js @@ -445,6 +445,106 @@ QUnit.test('Issue #209 - Grouping works when multiple rules are defined - Not Ob //#endregion +//#region Error Collection Tests + +QUnit.module('Error Collection Tests'); + +QUnit.test('find returns first element matching predicate', function (assert) { + + var vm = { + one: ko.observable().extend({ digit: true }), + two: ko.observable().extend({ max: 10 }) + }; + + var errors = ko.validation.group(vm, { observable: false }); + + vm.one('abc'); + vm.two(11); + + assert.equal(errors.find(function(val) { + return val() === 11; + })(), 11); +}); + +QUnit.test('filter returns all elements matching predicate', function (assert) { + + var vm = { + one: ko.observable().extend({ digit: true }), + two: ko.observable().extend({ max: 10 }), + three: ko.observable().extend({ max: 15 }) + }; + + var errors = ko.validation.group(vm, { observable: false }); + + vm.one('abc'); + vm.two(11); + vm.three(16); + + assert.equal(errors.filter(function (val) { + return val.rules()[0].rule === 'max'; + }).length, 2); +}); + +QUnit.test('forEach calls back for each error', 2, function (assert) { + + var vm = { + one: ko.observable().extend({ digit: true }), + two: ko.observable().extend({ max: 10 }) + }; + + var errors = ko.validation.group(vm, { observable: false }); + + vm.one('abc'); + vm.two(11); + + errors.forEach(function() { + assert.ok(true); + }); +}); + +QUnit.test('map returns projection for each error', function (assert) { + + var vm = { + one: ko.observable().extend({ digit: true }), + two: ko.observable().extend({ max: 10 }) + }; + + var errors = ko.validation.group(vm, { observable: false }); + + vm.one('abc'); + vm.two(11); + + var result = errors.map(function(item) { + return item.rules()[0].rule; + }); + + assert.equal(result[0], 'digit'); + assert.equal(result[1], 'max'); +}); + +QUnit.test('collection methods include error information', function(assert) { + var vm = { + one: ko.observable().extend({ digit: true }) + }; + + var errors = ko.validation.group(vm, { observable: false }); + + vm.one('abc'); + errors.forEach(function(item) { + assert.ok( + !!item.error && + !!item.isValid && + !!item.isModified && + !!item.isValidating && + !!item.rules && + !!item.setError && + !!item.clearError + ); + }); +}); + +//#endregion + //#region validatedObservable QUnit.module('validatedObservable Tests'); From 4036f16f82a99cb231eb574d2072be7c149275a7 Mon Sep 17 00:00:00 2001 From: crissdev Date: Thu, 8 Jan 2015 23:48:52 +0200 Subject: [PATCH 121/165] ko.validation.group should not resolve deferred computed values ko.validation.group will not resolve deferred computed values unless they have rules defined on them. Closes #163 --- Dist/knockout.validation.js | 2 +- Dist/knockout.validation.min.js | 2 +- Dist/knockout.validation.min.js.map | 2 +- Src/api.js | 2 +- Tests/utils-tests.js | 40 +++++++++++++++++++++++++++++ 5 files changed, 44 insertions(+), 4 deletions(-) diff --git a/Dist/knockout.validation.js b/Dist/knockout.validation.js index 0bda9f78..718be5a2 100644 --- a/Dist/knockout.validation.js +++ b/Dist/knockout.validation.js @@ -274,7 +274,7 @@ kv.configuration = configuration; if (level !== 0) { utils.forEach(objValues, function (observable) { //but not falsy things and not HTML Elements - if (observable && !observable.nodeType) { + if (observable && !observable.nodeType && (!ko.isComputed(observable) || observable.rules)) { traverseGraph(observable, context, level + 1); } }); diff --git a/Dist/knockout.validation.min.js b/Dist/knockout.validation.min.js index 2685ae98..dd2be73f 100644 --- a/Dist/knockout.validation.min.js +++ b/Dist/knockout.validation.min.js @@ -7,5 +7,5 @@ =============================================================================== */ -!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||e instanceof Date||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for week input. Should look like '2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for month input. Should look like '2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:h(c.params))?!0:(a.setError(f.formatMessage(c.message||b.message,h(c.params),a)),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,h(c.params),a)),a.__valid__(e)),void a.isValidating(!1)):void a.isValidating(!1)};b.validator(a(),h(c.params||!0),d)}if("undefined"==typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0,live:!1},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},isNumber:function(a){return!isNaN(a)},isObservableArray:function(a){return!!a&&"function"==typeof a.remove&&"function"==typeof a.removeAll&&"function"==typeof a.destroy&&"function"==typeof a.destroyAll&&"function"==typeof a.indexOf&&"function"==typeof a.replace},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return!!(a&&a.rules&&a.isValid&&a.isModified)},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},forEach:function(a,b){if(f.utils.isArray(a))return i(a,b);for(var c in a)a.hasOwnProperty(c)&&b(a[c],c)}}}();var m=function(){function b(a){i(a.subscriptions,function(a){a.dispose()}),a.subscriptions=[]}function c(a){a.options.deep&&(i(a.flagged,function(a){delete a.__kv_traversed}),a.flagged.length=0),a.options.live||b(a)}function d(a,d){d.validatables=[],b(d),e(a,d),c(d)}function e(b,c,d){var f=[],g=b.peek?b.peek():b;b.__kv_traversed!==!0&&(c.options.deep&&(b.__kv_traversed=!0,c.flagged.push(b)),d=void 0!==d?d:c.options.deep?1:-1,a.isObservable(b)&&(b.errors||n.isValidatable(b)||b.extend({validatable:!0}),c.validatables.push(b),c.options.live&&n.isObservableArray(b)&&c.subscriptions.push(b.subscribe(function(){c.graphMonitor.valueHasMutated()}))),g&&!g._destroy&&(n.isArray(g)?f=g:n.isObject(g)&&(f=n.values(g))),0!==d&&n.forEach(f,function(a){a&&!a.nodeType&&e(a,c,d+1)}))}function k(a){var b=[];return i(a,function(a){n.isValidatable(a)&&!a.isValid()&&b.push(a.error.peek())}),b}var l=0,m=f.configuration,n=f.utils;return{init:function(a,b){l>0&&!b||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||m.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||m.errorMessageClass,j(m,a),m.registerExtenders&&f.registerExtenders(),l=1)},configure:function(a){f.init(a)},reset:f.configuration.reset,group:function(b,c){c=j(j({},m.grouping),c);var e={options:c,graphMonitor:a.observable(),flagged:[],subscriptions:[],validatables:[]},f=null;return f=c.observable?a.computed(function(){return e.graphMonitor(),d(b,e),k(e.validatables)}):function(){return d(b,e),k(e.validatables)},f.showAllMessages=function(a){void 0===a&&(a=!0),f.forEach(function(b){n.isValidatable(b)&&b.isModified(a)})},f.isAnyMessageShown=function(){var a;return a=!!f.find(function(a){return n.isValidatable(a)&&!a.isValid()&&a.isModified()})},f.filter=function(a){return a=a||function(){return!0},f(),g.arrayFilter(e.validatables,a)},f.find=function(a){return a=a||function(){return!0},f(),g.arrayFirst(e.validatables,a)},f.forEach=function(a){a=a||function(){},f(),i(e.validatables,a)},f.map=function(a){return a=a||function(a){return a},f(),g.arrayMap(e.validatables,a)},f._updateState=function(a){if(!n.isObject(a))throw new Error("An object is required.");return b=a,c.observable?void e.graphMonitor.valueHasMutated():(d(a,e),k(e.validatables))},f},formatMessage:function(a,b,c){if(n.isObject(b)&&b.typeAttr&&(b=b.value),"function"==typeof a)return a(b,c);var d=h(b)||[];return n.isArray(d)||(d=[d]),a.replace(/{(\d+)}/gi,function(a,b){return"undefined"!=typeof d[b]?d[b]:a})},addRule:function(a,b){a.extend({validatable:!0});var c=!!g.arrayFirst(a.rules(),function(a){return a.rule&&a.rule===b.rule});return c||a.rules.push(b),a},addAnonymousRule:function(a,b){void 0===b.message&&(b.message="Error"),b.onlyIf&&(b.condition=b.onlyIf),f.addRule(a,b)},addExtender:function(b){a.extenders[b]=function(a,c){return c&&(c.message||c.onlyIf)?f.addRule(a,{rule:b,message:c.message,params:n.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(m.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=n.getConfigOptions(a).errorMessageClass,n.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(n.hasAttribute(a,c)){var d=a.getAttribute(c)||!0;if("min"===c||"max"===c){var e=a.getAttribute("type");"undefined"!=typeof e&&e||(e="text"),d={typeAttr:e,value:d}}f.addRule(b(),{rule:c,params:d})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(b,c){var d=c();if(d&&d.rules){var e=d.rules();i(f.configuration.html5Attributes,function(c){var d=g.arrayFirst(e,function(a){return a.rule&&a.rule.toLowerCase()===c.toLowerCase()});d&&a.computed({read:function(){var e=a.unwrap(d.params);"pattern"===d.rule&&e instanceof RegExp&&(e=e.source),b.setAttribute(c,e)},disposeWhenNodeIsRemoved:b})}),e=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var d=function(b,c){if(b&&c)for(var e in c)if(c.hasOwnProperty(e)){var g=c[e];if(b[e]){var i=b[e],j=h(i),k={},l={};for(var m in g)g.hasOwnProperty(m)&&(f.rules[m]?k[m]=g[m]:l[m]=g[m]);if(a.isObservable(i)&&i.extend(k),j&&n.isArray(j))for(var o=0;o0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}."},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address."},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date."},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[-/](?:0?[1-9]|1[012])[-/](?:0?[1-9]|[12][0-9]|3[01])$/.test(a):!0},message:"Please enter a proper date."},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number."},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit."},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number."},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal."},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(c,function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateInputElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.textInput&&f.makeBindingHandlerValidatable("textInput"),f.makeBindingHandlerValidatable("selectedOptions"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),i=(h(d),!1),j=!1;if(null===d||"undefined"==typeof d)throw new Error("Cannot bind validationMessage to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");i=d.isModified(),j=d.isValid();var k=null;(!e.messagesOnModified||i)&&(k=j?null:d.error);var l=!e.messagesOnModified||i?!j:!1,m="none"!==b.style.display;e.allowHtmlMessages?g.setHtml(b,k):a.bindingHandlers.text.update(b,function(){return k}),m&&!l?b.style.display="none":!m&&l&&(b.style.display="")}},a.bindingHandlers.validationElement={update:function(b,c,d){var e=c(),g=f.utils.getConfigOptions(b),i=(h(e),!1),j=!1;if(null===e||"undefined"==typeof e)throw new Error("Cannot bind validationElement to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!e.isValid||!e.isModified)throw new Error("Observable is not validatable");i=e.isModified(),j=e.isValid();var k=function(){var a={},b=!g.decorateElementOnModified||i?!j:!1;return a[g.errorElementClass]=b,a};a.bindingHandlers.css.update(b,k,d),g.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!g.errorsAsTitleOnModified||i,c=f.utils.getOriginalElementTitle(b);return a&&!j?{title:e.error,"data-orig-title":c}:!a||j?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){var c=b.error.peek(),d=b.__valid__.peek();b.error(a),b.__valid__(!1),c===a||d||b.isValid.notifySubscribers()},b.clearError=function(){return b.error(null),b.__valid__(!0),b};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){b(),b.rules();return f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified.getSubscriptionsCount()>0&&(b.isModified._subscriptions.change=[]),b.isValidating.getSubscriptionsCount()>0&&(b.isValidating._subscriptions.change=[]),b.__valid__.getSubscriptionsCount()>0&&(b.__valid__._subscriptions.change=[]),g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=c.rule?f.rules[c.rule]:c,b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0},f.localize=function(a){var b;for(b in a)f.rules.hasOwnProperty(b)&&(f.rules[b].message=a[b])},a.applyBindingsWithValidation=function(b,c,d){var e,g=document.body;c&&c.nodeType?(g=c,e=d):e=c,f.init(),e&&(e=j(j({},f.configuration),e),f.utils.setDomData(g,e)),a.applyBindings(b,g)};var n=a.applyBindings;a.applyBindings=function(a,b){f.init(),n(a,b)},a.validatedObservable=function(b,c){if(!c&&!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var d=a.observable(b);return d.errors=f.group(f.utils.isObject(b)?b:{},c),d.isValid=a.observable(0===d.errors().length),a.isObservable(d.errors)?d.errors.subscribe(function(a){d.isValid(0===a.length)}):a.computed(d.errors).subscribe(function(a){d.isValid(0===a.length)}),d.subscribe(function(a){f.utils.isObject(a)||(a={}),d.errors._updateState(a),d.isValid(0===d.errors().length)}),d}}); +!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||e instanceof Date||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for week input. Should look like '2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw"Invalid value for "+a+" attribute for month input. Should look like '2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min";return j=e.match(h),j?b?i[1]j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:h(c.params))?!0:(a.setError(f.formatMessage(c.message||b.message,h(c.params),a)),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,h(c.params),a)),a.__valid__(e)),void a.isValidating(!1)):void a.isValidating(!1)};b.validator(a(),h(c.params||!0),d)}if("undefined"==typeof a)throw"Knockout is required, please ensure it is loaded before loading this validation plug-in";a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0,live:!1},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},isNumber:function(a){return!isNaN(a)},isObservableArray:function(a){return!!a&&"function"==typeof a.remove&&"function"==typeof a.removeAll&&"function"==typeof a.destroy&&"function"==typeof a.destroyAll&&"function"==typeof a.indexOf&&"function"==typeof a.replace},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return!!(a&&a.rules&&a.isValid&&a.isModified)},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},forEach:function(a,b){if(f.utils.isArray(a))return i(a,b);for(var c in a)a.hasOwnProperty(c)&&b(a[c],c)}}}();var m=function(){function b(a){i(a.subscriptions,function(a){a.dispose()}),a.subscriptions=[]}function c(a){a.options.deep&&(i(a.flagged,function(a){delete a.__kv_traversed}),a.flagged.length=0),a.options.live||b(a)}function d(a,d){d.validatables=[],b(d),e(a,d),c(d)}function e(b,c,d){var f=[],g=b.peek?b.peek():b;b.__kv_traversed!==!0&&(c.options.deep&&(b.__kv_traversed=!0,c.flagged.push(b)),d=void 0!==d?d:c.options.deep?1:-1,a.isObservable(b)&&(b.errors||n.isValidatable(b)||b.extend({validatable:!0}),c.validatables.push(b),c.options.live&&n.isObservableArray(b)&&c.subscriptions.push(b.subscribe(function(){c.graphMonitor.valueHasMutated()}))),g&&!g._destroy&&(n.isArray(g)?f=g:n.isObject(g)&&(f=n.values(g))),0!==d&&n.forEach(f,function(b){!b||b.nodeType||a.isComputed(b)&&!b.rules||e(b,c,d+1)}))}function k(a){var b=[];return i(a,function(a){n.isValidatable(a)&&!a.isValid()&&b.push(a.error.peek())}),b}var l=0,m=f.configuration,n=f.utils;return{init:function(a,b){l>0&&!b||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||m.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||m.errorMessageClass,j(m,a),m.registerExtenders&&f.registerExtenders(),l=1)},configure:function(a){f.init(a)},reset:f.configuration.reset,group:function(b,c){c=j(j({},m.grouping),c);var e={options:c,graphMonitor:a.observable(),flagged:[],subscriptions:[],validatables:[]},f=null;return f=c.observable?a.computed(function(){return e.graphMonitor(),d(b,e),k(e.validatables)}):function(){return d(b,e),k(e.validatables)},f.showAllMessages=function(a){void 0===a&&(a=!0),f.forEach(function(b){n.isValidatable(b)&&b.isModified(a)})},f.isAnyMessageShown=function(){var a;return a=!!f.find(function(a){return n.isValidatable(a)&&!a.isValid()&&a.isModified()})},f.filter=function(a){return a=a||function(){return!0},f(),g.arrayFilter(e.validatables,a)},f.find=function(a){return a=a||function(){return!0},f(),g.arrayFirst(e.validatables,a)},f.forEach=function(a){a=a||function(){},f(),i(e.validatables,a)},f.map=function(a){return a=a||function(a){return a},f(),g.arrayMap(e.validatables,a)},f._updateState=function(a){if(!n.isObject(a))throw new Error("An object is required.");return b=a,c.observable?void e.graphMonitor.valueHasMutated():(d(a,e),k(e.validatables))},f},formatMessage:function(a,b,c){if(n.isObject(b)&&b.typeAttr&&(b=b.value),"function"==typeof a)return a(b,c);var d=h(b)||[];return n.isArray(d)||(d=[d]),a.replace(/{(\d+)}/gi,function(a,b){return"undefined"!=typeof d[b]?d[b]:a})},addRule:function(a,b){a.extend({validatable:!0});var c=!!g.arrayFirst(a.rules(),function(a){return a.rule&&a.rule===b.rule});return c||a.rules.push(b),a},addAnonymousRule:function(a,b){void 0===b.message&&(b.message="Error"),b.onlyIf&&(b.condition=b.onlyIf),f.addRule(a,b)},addExtender:function(b){a.extenders[b]=function(a,c){return c&&(c.message||c.onlyIf)?f.addRule(a,{rule:b,message:c.message,params:n.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(m.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=n.getConfigOptions(a).errorMessageClass,n.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(n.hasAttribute(a,c)){var d=a.getAttribute(c)||!0;if("min"===c||"max"===c){var e=a.getAttribute("type");"undefined"!=typeof e&&e||(e="text"),d={typeAttr:e,value:d}}f.addRule(b(),{rule:c,params:d})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(b,c){var d=c();if(d&&d.rules){var e=d.rules();i(f.configuration.html5Attributes,function(c){var d=g.arrayFirst(e,function(a){return a.rule&&a.rule.toLowerCase()===c.toLowerCase()});d&&a.computed({read:function(){var e=a.unwrap(d.params);"pattern"===d.rule&&e instanceof RegExp&&(e=e.source),b.setAttribute(c,e)},disposeWhenNodeIsRemoved:b})}),e=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var d=function(b,c){if(b&&c)for(var e in c)if(c.hasOwnProperty(e)){var g=c[e];if(b[e]){var i=b[e],j=h(i),k={},l={};for(var m in g)g.hasOwnProperty(m)&&(f.rules[m]?k[m]=g[m]:l[m]=g[m]);if(a.isObservable(i)&&i.extend(k),j&&n.isArray(j))for(var o=0;o0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}."},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address."},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date."},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[-/](?:0?[1-9]|1[012])[-/](?:0?[1-9]|[12][0-9]|3[01])$/.test(a):!0},message:"Please enter a proper date."},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number."},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit."},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number."},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal."},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(c,function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateInputElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.textInput&&f.makeBindingHandlerValidatable("textInput"),f.makeBindingHandlerValidatable("selectedOptions"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),i=(h(d),!1),j=!1;if(null===d||"undefined"==typeof d)throw new Error("Cannot bind validationMessage to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!d.isValid||!d.isModified)throw new Error("Observable is not validatable");i=d.isModified(),j=d.isValid();var k=null;(!e.messagesOnModified||i)&&(k=j?null:d.error);var l=!e.messagesOnModified||i?!j:!1,m="none"!==b.style.display;e.allowHtmlMessages?g.setHtml(b,k):a.bindingHandlers.text.update(b,function(){return k}),m&&!l?b.style.display="none":!m&&l&&(b.style.display="")}},a.bindingHandlers.validationElement={update:function(b,c,d){var e=c(),g=f.utils.getConfigOptions(b),i=(h(e),!1),j=!1;if(null===e||"undefined"==typeof e)throw new Error("Cannot bind validationElement to undefined value. data-bind expression: "+b.getAttribute("data-bind"));if(!e.isValid||!e.isModified)throw new Error("Observable is not validatable");i=e.isModified(),j=e.isValid();var k=function(){var a={},b=!g.decorateElementOnModified||i?!j:!1;return a[g.errorElementClass]=b,a};a.bindingHandlers.css.update(b,k,d),g.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!g.errorsAsTitleOnModified||i,c=f.utils.getOriginalElementTitle(b);return a&&!j?{title:e.error,"data-orig-title":c}:!a||j?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){var c=b.error.peek(),d=b.__valid__.peek();b.error(a),b.__valid__(!1),c===a||d||b.isValid.notifySubscribers()},b.clearError=function(){return b.error(null),b.__valid__(!0),b};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){b(),b.rules();return f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),b.isModified.getSubscriptionsCount()>0&&(b.isModified._subscriptions.change=[]),b.isValidating.getSubscriptionsCount()>0&&(b.isValidating._subscriptions.change=[]),b.__valid__.getSubscriptionsCount()>0&&(b.__valid__._subscriptions.change=[]),g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=c.rule?f.rules[c.rule]:c,b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0},f.localize=function(a){var b;for(b in a)f.rules.hasOwnProperty(b)&&(f.rules[b].message=a[b])},a.applyBindingsWithValidation=function(b,c,d){var e,g=document.body;c&&c.nodeType?(g=c,e=d):e=c,f.init(),e&&(e=j(j({},f.configuration),e),f.utils.setDomData(g,e)),a.applyBindings(b,g)};var n=a.applyBindings;a.applyBindings=function(a,b){f.init(),n(a,b)},a.validatedObservable=function(b,c){if(!c&&!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var d=a.observable(b);return d.errors=f.group(f.utils.isObject(b)?b:{},c),d.isValid=a.observable(0===d.errors().length),a.isObservable(d.errors)?d.errors.subscribe(function(a){d.isValid(0===a.length)}):a.computed(d.errors).subscribe(function(a){d.isValid(0===a.length)}),d.subscribe(function(a){f.utils.isObject(a)||(a={}),d.errors._updateState(a),d.isValid(0===d.errors().length)}),d}}); //# sourceMappingURL=knockout.validation.min.js.map \ No newline at end of file diff --git a/Dist/knockout.validation.min.js.map b/Dist/knockout.validation.min.js.map index a09c842c..a28fc852 100644 --- a/Dist/knockout.validation.min.js.map +++ b/Dist/knockout.validation.min.js.map @@ -1 +1 @@ -{"version":3,"file":"knockout.validation.min.js","sources":["knockout.validation.js"],"names":["factory","require","exports","module","define","ko","validation","minMaxValidatorFactory","validatorName","isMaxValidation","val","options","kv","utils","isEmptyVal","comparisonValue","type","undefined","typeAttr","value","isNaN","Date","regex","valMatches","comparisonValueMatches","toLowerCase","match","parseFloat","validateSync","observable","rule","ctx","validator","params","unwrap","setError","formatMessage","message","validateAsync","isValidating","callBack","valObj","isValid","msg","__valid__","error","koUtils","unwrapObservable","forEach","arrayForEach","extend","defaults","registerExtenders","messagesOnModified","errorsAsTitle","errorsAsTitleOnModified","messageTemplate","insertMessages","parseInputAttributes","writeInputAttributes","decorateInputElement","decorateElementOnModified","errorClass","errorElementClass","errorMessageClass","allowHtmlMessages","grouping","deep","live","validate","configuration","html5Attributes","html5InputTypes","reset","seedId","getTime","domData","domDataKey","isArray","o","Object","prototype","toString","call","isObject","isNumber","isObservableArray","instance","values","r","i","hasOwnProperty","push","getValue","hasAttribute","node","attr","getAttribute","element","setAttribute","isValidatable","rules","isModified","insertAfter","newNode","parentNode","insertBefore","nextSibling","newId","getConfigOptions","contextFor","setDomData","data","key","getDomData","nodeType","context","getOriginalElementTitle","savedOriginalTitle","currentTitle","title","hasSavedOriginalTitle","async","expr","window","setImmediate","setTimeout","object","callback","prop","api","cleanUpSubscriptions","subscriptions","subscription","dispose","flagged","obj","__kv_traversed","length","runTraversal","validatables","traverseGraph","level","objValues","peek","isObservable","errors","validatable","subscribe","graphMonitor","valueHasMutated","_destroy","collectErrors","array","isInitialized","init","force","configure","group","result","computed","showAllMessages","show","isAnyMessageShown","invalidAndModifiedPresent","find","filter","predicate","arrayFilter","arrayFirst","map","mapping","item","arrayMap","_updateState","newValue","Error","replacements","replace","index","addRule","hasRule","addAnonymousRule","ruleObj","onlyIf","condition","addExtender","ruleName","extenders","insertValidationMessage","span","document","createElement","className","parseInputValidationAttributes","valueAccessor","currentType","writeInputValidationAttributes","contexts","read","RegExp","source","disposeWhenNodeIsRemoved","makeBindingHandlerValidatable","handlerName","bindingHandlers","allBindingsAccessor","viewModel","bindingContext","setRules","target","definition","ruleDefinitions","targetValue","unwrappedTargetValue","nonRules","required","testVal","String","trim","minLength","normalizedVal","maxLength","step","dif","Math","abs","test","phoneNumber","otherValue","c","collection","external","externalValue","counter","config","validationMessageElement","renderTemplate","field","applyBindingsToNode","validationMessage","validationElement","textInput","update","obsv","isVisible","isCurrentlyVisible","style","display","setHtml","text","cssSettingsAccessor","css","shouldShow","hasModification","data-orig-title","newConfig","enable","validationOptions","throttleEvaluation","throttle","observableArray","previousError","previousIsValid","notifySubscribers","clearError","h_change","h_obsValidationTrigger","validateObservable","_disposeValidation","removeAll","getSubscriptionsCount","_subscriptions","ruleContexts","len","localize","msgTranslations","applyBindingsWithValidation","rootNode","body","applyBindings","origApplyBindings","validatedObservable","initialValue"],"mappings":";;;;;;;;;CAUC,SAAUA,GAGgB,kBAAZC,UAA6C,gBAAZC,UAA0C,gBAAXC,QAEvEH,EAAQC,QAAQ,YAAaC,SACJ,kBAAXE,SAAyBA,OAAY,IAEnDA,QAAQ,WAAY,WAAYJ,GAGhCA,EAAQK,GAAIA,GAAGC,gBAErB,SAAWD,EAAIH,GA2tBjB,QAASK,GAAuBC,GAC5B,GAAIC,GAAoC,QAAlBD,CAEtB,OAAO,UAAUE,EAAKC,GAClB,GAAIC,EAAGC,MAAMC,WAAWJ,GACpB,OAAO,CAGX,IAAIK,GAAiBC,CACIC,UAArBN,EAAQO,UAGRF,EAAO,OACPD,EAAkBJ,IAElBK,EAAOL,EAAQO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0M,EAAKlG,SAASR,UAGrB0G"} \ No newline at end of file +{"version":3,"file":"knockout.validation.min.js","sources":["knockout.validation.js"],"names":["factory","require","exports","module","define","ko","validation","minMaxValidatorFactory","validatorName","isMaxValidation","val","options","kv","utils","isEmptyVal","comparisonValue","type","undefined","typeAttr","value","isNaN","Date","regex","valMatches","comparisonValueMatches","toLowerCase","match","parseFloat","validateSync","observable","rule","ctx","validator","params","unwrap","setError","formatMessage","message","validateAsync","isValidating","callBack","valObj","isValid","msg","__valid__","error","koUtils","unwrapObservable","forEach","arrayForEach","extend","defaults","registerExtenders","messagesOnModified","errorsAsTitle","errorsAsTitleOnModified","messageTemplate","insertMessages","parseInputAttributes","writeInputAttributes","decorateInputElement","decorateElementOnModified","errorClass","errorElementClass","errorMessageClass","allowHtmlMessages","grouping","deep","live","validate","configuration","html5Attributes","html5InputTypes","reset","seedId","getTime","domData","domDataKey","isArray","o","Object","prototype","toString","call","isObject","isNumber","isObservableArray","instance","values","r","i","hasOwnProperty","push","getValue","hasAttribute","node","attr","getAttribute","element","setAttribute","isValidatable","rules","isModified","insertAfter","newNode","parentNode","insertBefore","nextSibling","newId","getConfigOptions","contextFor","setDomData","data","key","getDomData","nodeType","context","getOriginalElementTitle","savedOriginalTitle","currentTitle","title","hasSavedOriginalTitle","async","expr","window","setImmediate","setTimeout","object","callback","prop","api","cleanUpSubscriptions","subscriptions","subscription","dispose","flagged","obj","__kv_traversed","length","runTraversal","validatables","traverseGraph","level","objValues","peek","isObservable","errors","validatable","subscribe","graphMonitor","valueHasMutated","_destroy","isComputed","collectErrors","array","isInitialized","init","force","configure","group","result","computed","showAllMessages","show","isAnyMessageShown","invalidAndModifiedPresent","find","filter","predicate","arrayFilter","arrayFirst","map","mapping","item","arrayMap","_updateState","newValue","Error","replacements","replace","index","addRule","hasRule","addAnonymousRule","ruleObj","onlyIf","condition","addExtender","ruleName","extenders","insertValidationMessage","span","document","createElement","className","parseInputValidationAttributes","valueAccessor","currentType","writeInputValidationAttributes","contexts","read","RegExp","source","disposeWhenNodeIsRemoved","makeBindingHandlerValidatable","handlerName","bindingHandlers","allBindingsAccessor","viewModel","bindingContext","setRules","target","definition","ruleDefinitions","targetValue","unwrappedTargetValue","nonRules","required","testVal","String","trim","minLength","normalizedVal","maxLength","step","dif","Math","abs","test","phoneNumber","otherValue","c","collection","external","externalValue","counter","config","validationMessageElement","renderTemplate","field","applyBindingsToNode","validationMessage","validationElement","textInput","update","obsv","isVisible","isCurrentlyVisible","style","display","setHtml","text","cssSettingsAccessor","css","shouldShow","hasModification","data-orig-title","newConfig","enable","validationOptions","throttleEvaluation","throttle","observableArray","previousError","previousIsValid","notifySubscribers","clearError","h_change","h_obsValidationTrigger","validateObservable","_disposeValidation","removeAll","getSubscriptionsCount","_subscriptions","ruleContexts","len","localize","msgTranslations","applyBindingsWithValidation","rootNode","body","applyBindings","origApplyBindings","validatedObservable","initialValue"],"mappings":";;;;;;;;;CAUC,SAAUA,GAGgB,kBAAZC,UAA6C,gBAAZC,UAA0C,gBAAXC,QAEvEH,EAAQC,QAAQ,YAAaC,SACJ,kBAAXE,SAAyBA,OAAY,IAEnDA,QAAQ,WAAY,WAAYJ,GAGhCA,EAAQK,GAAIA,GAAGC,gBAErB,SAAWD,EAAIH,GA2tBjB,QAASK,GAAuBC,GAC5B,GAAIC,GAAoC,QAAlBD,CAEtB,OAAO,UAAUE,EAAKC,GAClB,GAAIC,EAAGC,MAAMC,WAAWJ,GACpB,OAAO,CAGX,IAAIK,GAAiBC,CACIC,UAArBN,EAAQO,UAGRF,EAAO,OACPD,EAAkBJ,IAElBK,EAAOL,EAAQO,SACfH,EAAkBJ,EAAQQ,OAKzBC,MAAML,IAAsBA,YAA2BM,QACxDL,EAAO,SAGX,IAAIM,GAAOC,EAAYC,CACvB,QAAQR,EAAKS,eACT,IAAK,OAGD,GAFAH,EAAQ,qBACRC,EAAab,EAAIgB,MAAMJ,GACJ,OAAfC,EACA,KAAM,qBAAuBf,EAAgB,+HAKjD,OAFA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GADG7I,EAAOiG,SAASwF,IAGhBD,IAAYA,EAASpK,UACxBpB,EAAOwL,EACP3C,EAASjO,GAGTiO,EAAS2C,EAGV3Q,EAAGgJ,OAECgF,IACHA,EAAS1L,EAAOA,KAAWtC,EAAG0D,eAAgBsK,GAC9ChO,EAAGC,MAAMkG,WAAWhB,EAAM6I,IAG3BvO,EAAGoR,cAAczE,EAAWjH,GAI7B,IAAI2L,GAAoBrR,EAAGoR,aAC3BpR,GAAGoR,cAAgB,SAAUzE,EAAWuE,GAEvC3Q,EAAGgJ,OAEH8H,EAAkB1E,EAAWuE,IAG9BlR,EAAGsR,oBAAsB,SAAUC,EAAcjR,GAChD,IAAKA,IAAYC,EAAGC,MAAMuE,SAASwM,GAClC,MAAOvR,GAAGwB,WAAW+P,GAAc1O,QAASiG,aAAa,GAG1D,IAAIkG,GAAOhP,EAAGwB,WAAW+P,EA6BzB,OA5BAvC,GAAKnG,OAAStI,EAAGmJ,MAAMnJ,EAAGC,MAAMuE,SAASwM,GAAgBA,KAAmBjR,GAC5E0O,EAAK3M,QAAUrC,EAAGwB,WAAoC,IAAzBwN,EAAKnG,SAASR,QAEvCrI,EAAG4I,aAAaoG,EAAKnG,QACxBmG,EAAKnG,OAAOE,UAAU,SAASF,GAC9BmG,EAAK3M,QAA0B,IAAlBwG,EAAOR,UAIrBrI,EAAG4J,SAASoF,EAAKnG,QAAQE,UAAU,SAAUF,GAC5CmG,EAAK3M,QAA0B,IAAlBwG,EAAOR,UAItB2G,EAAKjG,UAAU,SAAS4B,GAClBpK,EAAGC,MAAMuE,SAAS4F,KAMtBA,MAGDqE,EAAKnG,OAAO6B,aAAaC,GACzBqE,EAAK3M,QAAiC,IAAzB2M,EAAKnG,SAASR,UAGrB2G"} \ No newline at end of file diff --git a/Src/api.js b/Src/api.js index 6f134eff..eb0123b4 100644 --- a/Src/api.js +++ b/Src/api.js @@ -78,7 +78,7 @@ if (level !== 0) { utils.forEach(objValues, function (observable) { //but not falsy things and not HTML Elements - if (observable && !observable.nodeType) { + if (observable && !observable.nodeType && (!ko.isComputed(observable) || observable.rules)) { traverseGraph(observable, context, level + 1); } }); diff --git a/Tests/utils-tests.js b/Tests/utils-tests.js index 8daab375..437694b3 100644 --- a/Tests/utils-tests.js +++ b/Tests/utils-tests.js @@ -163,4 +163,44 @@ QUnit.test('isObservableArray returns true for observable arrays', function(asse assert.ok(!ko.validation.utils.isObservableArray(undefined)); }); +QUnit.test('Group does not resolve deferred computed values', function(assert) { + var vm = { + Value: ko.observable('no') + }; + vm.Test = ko.computed({ + read: function() { + vm.Value('yes'); + }, + deferEvaluation: true + }); + + assert.equal(vm.Value(), 'no', 'Not resolved'); + var errors = ko.validation.group(vm); + + assert.equal(vm.Value(), 'no', 'Still not resolved'); + assert.equal(errors().length, 0, 'No errors'); +}); + +QUnit.test('Group does resolve deferred computed values that have validation', function(assert) { + var vm = { + Value: ko.observable('no') + }; + vm.Test = ko.computed({ + read: function() { + vm.Value('yes'); + }, + deferEvaluation: true + }); + + assert.equal(vm.Value(), 'no', 'Not resolved'); + + vm.Test.extend({required: true}); + var errors = ko.validation.group(vm); + + assert.equal(vm.Value(), 'yes', 'Resolved'); + assert.equal(errors().length, 1, 'Error notification'); + assert.strictEqual(vm.Test.isValid(), false); + assert.equal(vm.Test.error(), 'This field is required.'); +}); + //#endregion From 26be53b797d931cf7fb92acd5fa7fc2285a5c191 Mon Sep 17 00:00:00 2001 From: crissdev Date: Mon, 5 Jan 2015 16:53:46 +0200 Subject: [PATCH 122/165] Add missing bower.json Closes #497 --- README.md | 37 +++++++++++++++++++++++++++++-------- bower.json | 29 +++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 8 deletions(-) create mode 100644 bower.json diff --git a/README.md b/README.md index fb54d1a4..05418754 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,9 @@ A KnockoutJS Plugin for model and property validation [![Build Status](https://travis-ci.org/Knockout-Contrib/Knockout-Validation.png)](https://travis-ci.org/Knockout-Contrib/Knockout-Validation) +[![Bower version](https://badge.fury.io/bo/knockout-validation.svg)](http://badge.fury.io/bo/knockout-validation) +[![npm version](https://badge.fury.io/js/knockout.validation.svg)](http://badge.fury.io/js/knockout.validation) +[![NuGet version](https://badge.fury.io/nu/Knockout.Validation.svg)](http://badge.fury.io/nu/Knockout.Validation) Contributors: @@ -13,16 +16,34 @@ Contributors: License: [MIT](http://www.opensource.org/licenses/mit-license.php) -###NuGet: [Knockout.Validation](http://nuget.org/packages/Knockout.Validation) -Tested in IE 6+, FF7, Chrome 15 +## Install + +#### Bower + +```sh +bower install knockout-validation --save-dev +``` + +#### NuGet + +```ps1 +PM> Install-Package Knockout.Validation +``` + +#### NPM + +```sh +npm install knockout.validation --save +``` + ##Getting Started ```javascript //start using it! var myValue = ko.observable().extend({ required: true }); //oooh complexity -var myComplexValue = ko.observable().extend({ +var myComplexValue = ko.observable().extend({ required: true, minLength: 3, pattern: { @@ -94,7 +115,7 @@ var myObj = ko.observable('').extend({ email: true }); _Much thanks to the [jQuery Validation Plug-In](https://github.com/jzaefferer/jquery-validation) team for their work on many of the rules_ ##Custom Validation Rules ####Custom Rules -Custom Rules can be created using the simple example below. All you need is to define a validator function and a default message. +Custom Rules can be created using the simple example below. All you need is to define a validator function and a default message. The validator function takes in the observable's value, and the `params` that you pass in with the `extend` method. ```javascript @@ -115,7 +136,7 @@ Learn more about Custom Rules on the [WIKI](https://github.com/Knockout-Contrib/ ##HTML5 Validation Attributes -**Required**: +**Required**: ```html @@ -129,7 +150,7 @@ Learn more about Custom Rules on the [WIKI](https://github.com/Knockout-Contrib/ ``` -**Max**: +**Max**: ```html @@ -137,13 +158,13 @@ Learn more about Custom Rules on the [WIKI](https://github.com/Knockout-Contrib/ ``` -**Pattern**: +**Pattern**: ```html ``` -**Step**: +**Step**: ```html diff --git a/bower.json b/bower.json new file mode 100644 index 00000000..9e14de1c --- /dev/null +++ b/bower.json @@ -0,0 +1,29 @@ +{ + "name": "knockout-validation", + "description": "A KnockoutJS Plugin for model and property validation", + "main": "Dist/knockout.validation.js", + "license": "MIT", + "ignore": [ + "**/.*", + "node_modules", + "Lib", + "Src", + "Scripts", + "Tests", + "gruntfile.js" + ], + "keywords": [ + "Knockout-Validation", + "knockout", + "validation", + "ko" + ], + "homepage": "https://github.com/Knockout-Contrib/Knockout-Validation", + "repository": { + "type": "git", + "url": "git://github.com/Knockout-Contrib/Knockout-Validation.git" + }, + "dependencies": { + "knockout": ">=2.3.0" + } +} From 19be2166404d2272df43bcdc704e16dadd64dae9 Mon Sep 17 00:00:00 2001 From: crissdev Date: Fri, 9 Jan 2015 18:48:18 +0200 Subject: [PATCH 123/165] Remove unnecessary markup from test runner QUnit will us the title element to create the #qunit-header. The other QUnit elements are automatically generated. --- Tests/test-runner.htm | 13 ++----------- package.json | 2 +- 2 files changed, 3 insertions(+), 12 deletions(-) diff --git a/Tests/test-runner.htm b/Tests/test-runner.htm index 93f80c5b..eae07c4f 100644 --- a/Tests/test-runner.htm +++ b/Tests/test-runner.htm @@ -24,17 +24,8 @@ -
          -

          Knockout JS Validation Tests

          -

          -
          -

          -
            -
            test markup, will be hidden
            -
            -
            - -
            +
            +
            - + + + + +``` + +Apply localized messages + +```js +ko.validation.locale('el-GR'); ``` diff --git a/Src/localization.js b/Src/localization.js index bc02c4ba..57a0ad46 100644 --- a/Src/localization.js +++ b/Src/localization.js @@ -1,4 +1,30 @@  +var _locales = {}; +var _currentLocale; + +ko.validation.defineLocale = function(name, values) { + if (name && values) { + _locales[name.toLowerCase()] = values; + return values; + } + return null; +}; + +ko.validation.locale = function(name) { + if (name) { + name = name.toLowerCase(); + + if (_locales.hasOwnProperty(name)) { + ko.validation.localize(_locales[name]); + _currentLocale = name; + } + else { + throw new Error('Localization ' + name + ' has not been loaded.'); + } + } + return _currentLocale; +}; + //quick function to override rule messages ko.validation.localize = function (msgTranslations) { var rules = ko.validation.rules; @@ -10,3 +36,19 @@ ko.validation.localize = function (msgTranslations) { } } }; + +// Populate default locale (this will make en-US.js somewhat redundant) +(function() { + var localeData = {}; + var rules = ko.validation.rules; + + for (var ruleName in rules) { + if (rules.hasOwnProperty(ruleName)) { + localeData[ruleName] = rules[ruleName].message; + } + } + ko.validation.defineLocale('en-us', localeData); +})(); + +// No need to invoke locale because the messages are already defined along with the rules for en-US +_currentLocale = 'en-us'; diff --git a/Tests/locale-tests.js b/Tests/locale-tests.js new file mode 100644 index 00000000..20e2b702 --- /dev/null +++ b/Tests/locale-tests.js @@ -0,0 +1,67 @@ +/*global QUnit:false*/ + +QUnit.module('Localization Tests', { + afterEach: function() { + ko.validation.locale('en-US'); + } +}); + +QUnit.test('Default locale should be en-us', function(assert) { + assert.equal(ko.validation.locale(), 'en-us'); +}); + +QUnit.test('Locale identifiers should be case insensitive', function(assert) { + assert.equal(ko.validation.locale('RO-RO'), 'ro-ro'); +}); + +QUnit.test('Changing locale should change rules messages', function(assert) { + ko.validation.locale('ro-RO'); + assert.equal(ko.validation.rules.required.message, 'Acest câmp este obligatoriu.'); +}); + +QUnit.test('Reverting to default locale is possible', function(assert) { + ko.validation.locale('ro-RO'); + assert.equal(ko.validation.locale(), 'ro-ro'); + assert.equal(ko.validation.rules.required.message, 'Acest câmp este obligatoriu.'); + + ko.validation.locale('en-us'); + assert.equal(ko.validation.locale(), 'en-us'); + assert.equal(ko.validation.rules.required.message, 'This field is required.'); +}); + +QUnit.test('Locale does not change when locale name is falsy', function(assert) { + var currentLocale = ko.validation.locale(); + assert.equal(currentLocale, 'en-us'); + + ko.validation.locale(null); + assert.equal(currentLocale, 'en-us'); + + ko.validation.locale(false); + assert.equal(currentLocale, 'en-us'); + + ko.validation.locale(undefined); + assert.equal(currentLocale, 'en-us'); + + ko.validation.locale(''); + assert.equal(currentLocale, 'en-us'); +}); + +QUnit.test('Changing locale to a not loaded language throws', function(assert) { + assert.throws(function() { + ko.validation.locale('fr-FR'); + }); +}); + +QUnit.test('Defining locales works', function(assert) { + var result = ko.validation.defineLocale('de-DE', { + required: 'Dieses Feld ist erforderlich.' + }); + assert.equal(ko.validation.locale('de-DE'), 'de-de'); + assert.equal(ko.validation.rules.required.message, 'Dieses Feld ist erforderlich.'); + + // Since the localization specified only required rule, the others should be left to their original values + assert.equal(ko.validation.rules.email.message, 'Please enter a proper email address.'); + + // defineLocale should return the values that were passed in + assert.deepEqual(result, {required: 'Dieses Feld ist erforderlich.'}); +}); diff --git a/Tests/test-runner.htm b/Tests/test-runner.htm index eae07c4f..e53ddce2 100644 --- a/Tests/test-runner.htm +++ b/Tests/test-runner.htm @@ -7,6 +7,7 @@ + @@ -15,6 +16,7 @@ + Knockout JS Validation Tests + + +
            +
            +
            + + +
            + User: errors + + +
            + + + +
            + + + + +
            + +
            +
            + + +
            + + diff --git a/test/test-runner-3.5.0.html b/test/test-runner-3.5.0.html new file mode 100644 index 00000000..bcc2ef57 --- /dev/null +++ b/test/test-runner-3.5.0.html @@ -0,0 +1,144 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Knockout JS Validation Tests (KnockoutJS v3.5.0) + + + +
            +
            +
            + + +
            + User: errors + + +
            + + + +
            + + + + +
            + +
            +
            + + +
            + + From b24c7d3d335d42dab59db2d8090b966241453160 Mon Sep 17 00:00:00 2001 From: SimmeNilsson <30928046+SimmeNilsson@users.noreply.github.com> Date: Mon, 3 Jun 2019 15:01:49 +0200 Subject: [PATCH 156/165] fix Sweedish translation It said 'Enter less than x characters' in Swedish while x characters is okay as well. Now it says 'Enter x characters or less.' Closes #668, closes #581 --- localization/sv-SE.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/localization/sv-SE.js b/localization/sv-SE.js index f77c913f..8caf630e 100644 --- a/localization/sv-SE.js +++ b/localization/sv-SE.js @@ -23,7 +23,7 @@ min: 'Fyll i ett värde som är större än eller lika med {0}', max: 'Fyll i ett värde som är mindre än eller lika med {0}', minLength: 'Fyll i minst {0} tecken', - maxLength: 'Fyll i färre än {0} tecken', + maxLength: 'Fyll i {0} tecken eller färre', pattern: 'Var god kontrollera värdet', step: 'Värdet måste ökas med {0}', email: 'Fyll i en korrekt e-postadress', From 3eb59a5c8b2c429b1a2439c2897a876e28d9a344 Mon Sep 17 00:00:00 2001 From: crissdev Date: Sat, 5 Oct 2019 07:51:11 +0300 Subject: [PATCH 157/165] upgrade QUnit testing framework --- test/api-tests.js | 187 +- test/lib/qunit-1.17.1.js | 2875 ------- .../lib/{qunit-1.17.1.css => qunit-2.9.2.css} | 220 +- test/lib/qunit-2.9.2.js | 6604 +++++++++++++++++ test/locale-tests.js | 132 +- test/test-runner-2.3.0.html | 4 +- test/test-runner-3.4.2.html | 4 +- test/test-runner-3.5.0.html | 4 +- test/validation-ui-tests.js | 1705 +++-- 9 files changed, 7810 insertions(+), 3925 deletions(-) delete mode 100644 test/lib/qunit-1.17.1.js rename test/lib/{qunit-1.17.1.css => qunit-2.9.2.css} (56%) create mode 100644 test/lib/qunit-2.9.2.js diff --git a/test/api-tests.js b/test/api-tests.js index 24fbcb9b..0c480d16 100644 --- a/test/api-tests.js +++ b/test/api-tests.js @@ -451,96 +451,97 @@ QUnit.module('Error Collection Tests'); QUnit.test('find returns first element matching predicate', function (assert) { - var vm = { - one: ko.observable().extend({ digit: true }), - two: ko.observable().extend({ max: 10 }) - }; + var vm = { + one: ko.observable().extend({ digit: true }), + two: ko.observable().extend({ max: 10 }) + }; - var errors = ko.validation.group(vm, { observable: false }); + var errors = ko.validation.group(vm, { observable: false }); - vm.one('abc'); - vm.two(11); + vm.one('abc'); + vm.two(11); - assert.equal(errors.find(function(val) { - return val() === 11; - })(), 11); + assert.equal(errors.find(function(val) { + return val() === 11; + })(), 11); }); QUnit.test('filter returns all elements matching predicate', function (assert) { - var vm = { - one: ko.observable().extend({ digit: true }), - two: ko.observable().extend({ max: 10 }), - three: ko.observable().extend({ max: 15 }) - }; + var vm = { + one: ko.observable().extend({ digit: true }), + two: ko.observable().extend({ max: 10 }), + three: ko.observable().extend({ max: 15 }) + }; - var errors = ko.validation.group(vm, { observable: false }); + var errors = ko.validation.group(vm, { observable: false }); - vm.one('abc'); - vm.two(11); - vm.three(16); + vm.one('abc'); + vm.two(11); + vm.three(16); - assert.equal(errors.filter(function (val) { - return val.rules()[0].rule === 'max'; - }).length, 2); + assert.equal(errors.filter(function (val) { + return val.rules()[0].rule === 'max'; + }).length, 2); }); -QUnit.test('forEach calls back for each error', 2, function (assert) { +QUnit.test('forEach calls back for each error', function (assert) { + assert.expect(2); - var vm = { - one: ko.observable().extend({ digit: true }), - two: ko.observable().extend({ max: 10 }) - }; + var vm = { + one: ko.observable().extend({ digit: true }), + two: ko.observable().extend({ max: 10 }) + }; - var errors = ko.validation.group(vm, { observable: false }); + var errors = ko.validation.group(vm, { observable: false }); - vm.one('abc'); - vm.two(11); + vm.one('abc'); + vm.two(11); - errors.forEach(function() { - assert.ok(true); - }); + errors.forEach(function() { + assert.ok(true); + }); }); QUnit.test('map returns projection for each error', function (assert) { - var vm = { - one: ko.observable().extend({ digit: true }), - two: ko.observable().extend({ max: 10 }) - }; + var vm = { + one: ko.observable().extend({ digit: true }), + two: ko.observable().extend({ max: 10 }) + }; - var errors = ko.validation.group(vm, { observable: false }); + var errors = ko.validation.group(vm, { observable: false }); - vm.one('abc'); - vm.two(11); + vm.one('abc'); + vm.two(11); - var result = errors.map(function(item) { - return item.rules()[0].rule; - }); + var result = errors.map(function(item) { + return item.rules()[0].rule; + }); - assert.equal(result[0], 'digit'); - assert.equal(result[1], 'max'); + assert.equal(result[0], 'digit'); + assert.equal(result[1], 'max'); }); QUnit.test('collection methods include error information', function(assert) { - var vm = { - one: ko.observable().extend({ digit: true }) - }; - - var errors = ko.validation.group(vm, { observable: false }); - - vm.one('abc'); - errors.forEach(function(item) { - assert.ok( - !!item.error && - !!item.isValid && - !!item.isModified && - !!item.isValidating && - !!item.rules && - !!item.setError && - !!item.clearError - ); - }); + var vm = { + one: ko.observable().extend({ digit: true }) + }; + + var errors = ko.validation.group(vm, { observable: false }); + + vm.one('abc'); + errors.forEach(function(item) { + assert.ok( + !!item.error && + !!item.isValid && + !!item.isModified && + !!item.isValidating && + !!item.rules && + !!item.setError && + !!item.clearError + ); + }); }); //#endregion @@ -631,24 +632,24 @@ QUnit.test('validatedObservable show error message when at least one invalid and }); QUnit.test('validatedObservable is Valid when not modified', function(assert) { - var obj = ko.validatedObservable({ - testObj: ko.observable('12345').extend({ minLength: 5 }), - testObj2: ko.observable('a').extend({ required: true }) - }); + var obj = ko.validatedObservable({ + testObj: ko.observable('12345').extend({ minLength: 5 }), + testObj2: ko.observable('a').extend({ required: true }) + }); - assert.ok(obj(), 'observable works'); - assert.ok(obj.isValid(), 'observable is valid'); + assert.ok(obj(), 'observable works'); + assert.ok(obj.isValid(), 'observable is valid'); }); QUnit.test('validatedObservable is not Valid when not modified', function(assert) { - var obj = ko.validatedObservable({ - testObj: ko.observable('').extend({ minLength: 5 }), - testObj2: ko.observable('').extend({ required: true }) - }); + var obj = ko.validatedObservable({ + testObj: ko.observable('').extend({ minLength: 5 }), + testObj2: ko.observable('').extend({ required: true }) + }); - assert.ok(obj(), 'observable works'); - assert.ok(!obj.isValid(), obj.errors()[0]); + assert.ok(obj(), 'observable works'); + assert.ok(!obj.isValid(), obj.errors()[0]); }); QUnit.test('Issue #454 - validatedObservable throws when config option grouping.observable is false', function(assert) { @@ -789,9 +790,9 @@ QUnit.test('setRules applies rules to all properties', function(assert) { } }, nestedArray: ko.observableArray([ - { property4: ko.observable(), ignoredProperty: ko.observable() }, - { property4: ko.observable(), ignoredProperty: ko.observable() }, - { property4: ko.observable(), ignoredProperty: ko.observable() } + { property4: ko.observable(), ignoredProperty: ko.observable() }, + { property4: ko.observable(), ignoredProperty: ko.observable() }, + { property4: ko.observable(), ignoredProperty: ko.observable() } ]) }; @@ -799,17 +800,17 @@ QUnit.test('setRules applies rules to all properties', function(assert) { //check that all rules have been applied assert.deepEqual(target.property1.rules(), [ - { rule: 'required', params: true }, - { rule: 'min', params: 10 }, - { rule: 'max', params: 99 } + { rule: 'required', params: true }, + { rule: 'min', params: 10 }, + { rule: 'max', params: 99 } ]); assert.deepEqual(target.child.property2.rules(), [ - { rule: 'pattern', message: 'Only AlphaNumeric please', params: '^[a-z0-9].$', condition: undefined } + { rule: 'pattern', message: 'Only AlphaNumeric please', params: '^[a-z0-9].$', condition: undefined } ]); assert.deepEqual(target.child.grandchild.property3.rules(), [ - { rule: 'number', params: true } + { rule: 'number', params: true } ]); for (var i = 0; i < target.nestedArray().length; i++) { @@ -873,12 +874,12 @@ QUnit.module('Removing Validation Tests'); QUnit.test('Basic Removal', function(assert) { var testObj = ko.observable('') - .extend({ min: 2 }); + .extend({ min: 2 }); testObj(3); var testFlag = false; - var changeFlag = false; + var changeFlag = false; assert.equal(testObj(), 3, 'observable still works'); assert.ok(testObj.isValid(), 'testObj is Valid'); @@ -887,9 +888,9 @@ QUnit.test('Basic Removal', function(assert) { testFlag = true; }); - testObj.isModified.subscribe(function() { - changeFlag = true; - }); + testObj.isModified.subscribe(function() { + changeFlag = true; + }); testObj.extend({ validatable: false }); @@ -978,12 +979,12 @@ QUnit.test('formatMessage may use multiple replacements', function(assert) { }); QUnit.test('Issue #547 - formatMessage fails when params is 0', function(assert) { - var params = 0, - message = 'Please enter a value greater than or equal to {0}.', - obsv = ko.observable(-1); + var params = 0, + message = 'Please enter a value greater than or equal to {0}.', + obsv = ko.observable(-1); - var result = ko.validation.formatMessage(message, params, obsv); - assert.equal(result, 'Please enter a value greater than or equal to 0.'); + var result = ko.validation.formatMessage(message, params, obsv); + assert.equal(result, 'Please enter a value greater than or equal to 0.'); }); diff --git a/test/lib/qunit-1.17.1.js b/test/lib/qunit-1.17.1.js deleted file mode 100644 index 006ca474..00000000 --- a/test/lib/qunit-1.17.1.js +++ /dev/null @@ -1,2875 +0,0 @@ -/*! - * QUnit 1.17.1 - * http://qunitjs.com/ - * - * Copyright jQuery Foundation and other contributors - * Released under the MIT license - * http://jquery.org/license - * - * Date: 2015-01-20T19:39Z - */ - -(function( window ) { - -var QUnit, - config, - onErrorFnPrev, - loggingCallbacks = {}, - fileName = ( sourceFromStacktrace( 0 ) || "" ).replace( /(:\d+)+\)?/, "" ).replace( /.+\//, "" ), - toString = Object.prototype.toString, - hasOwn = Object.prototype.hasOwnProperty, - // Keep a local reference to Date (GH-283) - Date = window.Date, - now = Date.now || function() { - return new Date().getTime(); - }, - globalStartCalled = false, - runStarted = false, - setTimeout = window.setTimeout, - clearTimeout = window.clearTimeout, - defined = { - document: window.document !== undefined, - setTimeout: window.setTimeout !== undefined, - sessionStorage: (function() { - var x = "qunit-test-string"; - try { - sessionStorage.setItem( x, x ); - sessionStorage.removeItem( x ); - return true; - } catch ( e ) { - return false; - } - }()) - }, - /** - * Provides a normalized error string, correcting an issue - * with IE 7 (and prior) where Error.prototype.toString is - * not properly implemented - * - * Based on http://es5.github.com/#x15.11.4.4 - * - * @param {String|Error} error - * @return {String} error message - */ - errorString = function( error ) { - var name, message, - errorString = error.toString(); - if ( errorString.substring( 0, 7 ) === "[object" ) { - name = error.name ? error.name.toString() : "Error"; - message = error.message ? error.message.toString() : ""; - if ( name && message ) { - return name + ": " + message; - } else if ( name ) { - return name; - } else if ( message ) { - return message; - } else { - return "Error"; - } - } else { - return errorString; - } - }, - /** - * Makes a clone of an object using only Array or Object as base, - * and copies over the own enumerable properties. - * - * @param {Object} obj - * @return {Object} New object with only the own properties (recursively). - */ - objectValues = function( obj ) { - var key, val, - vals = QUnit.is( "array", obj ) ? [] : {}; - for ( key in obj ) { - if ( hasOwn.call( obj, key ) ) { - val = obj[ key ]; - vals[ key ] = val === Object( val ) ? objectValues( val ) : val; - } - } - return vals; - }; - -QUnit = {}; - -/** - * Config object: Maintain internal state - * Later exposed as QUnit.config - * `config` initialized at top of scope - */ -config = { - // The queue of tests to run - queue: [], - - // block until document ready - blocking: true, - - // by default, run previously failed tests first - // very useful in combination with "Hide passed tests" checked - reorder: true, - - // by default, modify document.title when suite is done - altertitle: true, - - // by default, scroll to top of the page when suite is done - scrolltop: true, - - // when enabled, all tests must call expect() - requireExpects: false, - - // add checkboxes that are persisted in the query-string - // when enabled, the id is set to `true` as a `QUnit.config` property - urlConfig: [ - { - id: "hidepassed", - label: "Hide passed tests", - tooltip: "Only show tests and assertions that fail. Stored as query-strings." - }, - { - id: "noglobals", - label: "Check for Globals", - tooltip: "Enabling this will test if any test introduces new properties on the " + - "`window` object. Stored as query-strings." - }, - { - id: "notrycatch", - label: "No try-catch", - tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging " + - "exceptions in IE reasonable. Stored as query-strings." - } - ], - - // Set of all modules. - modules: [], - - // The first unnamed module - currentModule: { - name: "", - tests: [] - }, - - callbacks: {} -}; - -// Push a loose unnamed module to the modules collection -config.modules.push( config.currentModule ); - -// Initialize more QUnit.config and QUnit.urlParams -(function() { - var i, current, - location = window.location || { search: "", protocol: "file:" }, - params = location.search.slice( 1 ).split( "&" ), - length = params.length, - urlParams = {}; - - if ( params[ 0 ] ) { - for ( i = 0; i < length; i++ ) { - current = params[ i ].split( "=" ); - current[ 0 ] = decodeURIComponent( current[ 0 ] ); - - // allow just a key to turn on a flag, e.g., test.html?noglobals - current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true; - if ( urlParams[ current[ 0 ] ] ) { - urlParams[ current[ 0 ] ] = [].concat( urlParams[ current[ 0 ] ], current[ 1 ] ); - } else { - urlParams[ current[ 0 ] ] = current[ 1 ]; - } - } - } - - if ( urlParams.filter === true ) { - delete urlParams.filter; - } - - QUnit.urlParams = urlParams; - - // String search anywhere in moduleName+testName - config.filter = urlParams.filter; - - config.testId = []; - if ( urlParams.testId ) { - - // Ensure that urlParams.testId is an array - urlParams.testId = [].concat( urlParams.testId ); - for ( i = 0; i < urlParams.testId.length; i++ ) { - config.testId.push( urlParams.testId[ i ] ); - } - } - - // Figure out if we're running the tests from a server or not - QUnit.isLocal = location.protocol === "file:"; -}()); - -// Root QUnit object. -// `QUnit` initialized at top of scope -extend( QUnit, { - - // call on start of module test to prepend name to all tests - module: function( name, testEnvironment ) { - var currentModule = { - name: name, - testEnvironment: testEnvironment, - tests: [] - }; - - // DEPRECATED: handles setup/teardown functions, - // beforeEach and afterEach should be used instead - if ( testEnvironment && testEnvironment.setup ) { - testEnvironment.beforeEach = testEnvironment.setup; - delete testEnvironment.setup; - } - if ( testEnvironment && testEnvironment.teardown ) { - testEnvironment.afterEach = testEnvironment.teardown; - delete testEnvironment.teardown; - } - - config.modules.push( currentModule ); - config.currentModule = currentModule; - }, - - // DEPRECATED: QUnit.asyncTest() will be removed in QUnit 2.0. - asyncTest: function( testName, expected, callback ) { - if ( arguments.length === 2 ) { - callback = expected; - expected = null; - } - - QUnit.test( testName, expected, callback, true ); - }, - - test: function( testName, expected, callback, async ) { - var test; - - if ( arguments.length === 2 ) { - callback = expected; - expected = null; - } - - test = new Test({ - testName: testName, - expected: expected, - async: async, - callback: callback - }); - - test.queue(); - }, - - skip: function( testName ) { - var test = new Test({ - testName: testName, - skip: true - }); - - test.queue(); - }, - - // DEPRECATED: The functionality of QUnit.start() will be altered in QUnit 2.0. - // In QUnit 2.0, invoking it will ONLY affect the `QUnit.config.autostart` blocking behavior. - start: function( count ) { - var globalStartAlreadyCalled = globalStartCalled; - - if ( !config.current ) { - globalStartCalled = true; - - if ( runStarted ) { - throw new Error( "Called start() outside of a test context while already started" ); - } else if ( globalStartAlreadyCalled || count > 1 ) { - throw new Error( "Called start() outside of a test context too many times" ); - } else if ( config.autostart ) { - throw new Error( "Called start() outside of a test context when " + - "QUnit.config.autostart was true" ); - } else if ( !config.pageLoaded ) { - - // The page isn't completely loaded yet, so bail out and let `QUnit.load` handle it - config.autostart = true; - return; - } - } else { - - // If a test is running, adjust its semaphore - config.current.semaphore -= count || 1; - - // Don't start until equal number of stop-calls - if ( config.current.semaphore > 0 ) { - return; - } - - // throw an Error if start is called more often than stop - if ( config.current.semaphore < 0 ) { - config.current.semaphore = 0; - - QUnit.pushFailure( - "Called start() while already started (test's semaphore was 0 already)", - sourceFromStacktrace( 2 ) - ); - return; - } - } - - resumeProcessing(); - }, - - // DEPRECATED: QUnit.stop() will be removed in QUnit 2.0. - stop: function( count ) { - - // If there isn't a test running, don't allow QUnit.stop() to be called - if ( !config.current ) { - throw new Error( "Called stop() outside of a test context" ); - } - - // If a test is running, adjust its semaphore - config.current.semaphore += count || 1; - - pauseProcessing(); - }, - - config: config, - - // Safe object type checking - is: function( type, obj ) { - return QUnit.objectType( obj ) === type; - }, - - objectType: function( obj ) { - if ( typeof obj === "undefined" ) { - return "undefined"; - } - - // Consider: typeof null === object - if ( obj === null ) { - return "null"; - } - - var match = toString.call( obj ).match( /^\[object\s(.*)\]$/ ), - type = match && match[ 1 ] || ""; - - switch ( type ) { - case "Number": - if ( isNaN( obj ) ) { - return "nan"; - } - return "number"; - case "String": - case "Boolean": - case "Array": - case "Date": - case "RegExp": - case "Function": - return type.toLowerCase(); - } - if ( typeof obj === "object" ) { - return "object"; - } - return undefined; - }, - - extend: extend, - - load: function() { - config.pageLoaded = true; - - // Initialize the configuration options - extend( config, { - stats: { all: 0, bad: 0 }, - moduleStats: { all: 0, bad: 0 }, - started: 0, - updateRate: 1000, - autostart: true, - filter: "" - }, true ); - - config.blocking = false; - - if ( config.autostart ) { - resumeProcessing(); - } - } -}); - -// Register logging callbacks -(function() { - var i, l, key, - callbacks = [ "begin", "done", "log", "testStart", "testDone", - "moduleStart", "moduleDone" ]; - - function registerLoggingCallback( key ) { - var loggingCallback = function( callback ) { - if ( QUnit.objectType( callback ) !== "function" ) { - throw new Error( - "QUnit logging methods require a callback function as their first parameters." - ); - } - - config.callbacks[ key ].push( callback ); - }; - - // DEPRECATED: This will be removed on QUnit 2.0.0+ - // Stores the registered functions allowing restoring - // at verifyLoggingCallbacks() if modified - loggingCallbacks[ key ] = loggingCallback; - - return loggingCallback; - } - - for ( i = 0, l = callbacks.length; i < l; i++ ) { - key = callbacks[ i ]; - - // Initialize key collection of logging callback - if ( QUnit.objectType( config.callbacks[ key ] ) === "undefined" ) { - config.callbacks[ key ] = []; - } - - QUnit[ key ] = registerLoggingCallback( key ); - } -})(); - -// `onErrorFnPrev` initialized at top of scope -// Preserve other handlers -onErrorFnPrev = window.onerror; - -// Cover uncaught exceptions -// Returning true will suppress the default browser handler, -// returning false will let it run. -window.onerror = function( error, filePath, linerNr ) { - var ret = false; - if ( onErrorFnPrev ) { - ret = onErrorFnPrev( error, filePath, linerNr ); - } - - // Treat return value as window.onerror itself does, - // Only do our handling if not suppressed. - if ( ret !== true ) { - if ( QUnit.config.current ) { - if ( QUnit.config.current.ignoreGlobalErrors ) { - return true; - } - QUnit.pushFailure( error, filePath + ":" + linerNr ); - } else { - QUnit.test( "global failure", extend(function() { - QUnit.pushFailure( error, filePath + ":" + linerNr ); - }, { validTest: true } ) ); - } - return false; - } - - return ret; -}; - -function done() { - var runtime, passed; - - config.autorun = true; - - // Log the last module results - if ( config.previousModule ) { - runLoggingCallbacks( "moduleDone", { - name: config.previousModule.name, - tests: config.previousModule.tests, - failed: config.moduleStats.bad, - passed: config.moduleStats.all - config.moduleStats.bad, - total: config.moduleStats.all, - runtime: now() - config.moduleStats.started - }); - } - delete config.previousModule; - - runtime = now() - config.started; - passed = config.stats.all - config.stats.bad; - - runLoggingCallbacks( "done", { - failed: config.stats.bad, - passed: passed, - total: config.stats.all, - runtime: runtime - }); -} - -// Doesn't support IE6 to IE9 -// See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack -function extractStacktrace( e, offset ) { - offset = offset === undefined ? 4 : offset; - - var stack, include, i; - - if ( e.stacktrace ) { - - // Opera 12.x - return e.stacktrace.split( "\n" )[ offset + 3 ]; - } else if ( e.stack ) { - - // Firefox, Chrome, Safari 6+, IE10+, PhantomJS and Node - stack = e.stack.split( "\n" ); - if ( /^error$/i.test( stack[ 0 ] ) ) { - stack.shift(); - } - if ( fileName ) { - include = []; - for ( i = offset; i < stack.length; i++ ) { - if ( stack[ i ].indexOf( fileName ) !== -1 ) { - break; - } - include.push( stack[ i ] ); - } - if ( include.length ) { - return include.join( "\n" ); - } - } - return stack[ offset ]; - } else if ( e.sourceURL ) { - - // Safari < 6 - // exclude useless self-reference for generated Error objects - if ( /qunit.js$/.test( e.sourceURL ) ) { - return; - } - - // for actual exceptions, this is useful - return e.sourceURL + ":" + e.line; - } -} - -function sourceFromStacktrace( offset ) { - var e = new Error(); - if ( !e.stack ) { - try { - throw e; - } catch ( err ) { - // This should already be true in most browsers - e = err; - } - } - return extractStacktrace( e, offset ); -} - -function synchronize( callback, last ) { - if ( QUnit.objectType( callback ) === "array" ) { - while ( callback.length ) { - synchronize( callback.shift() ); - } - return; - } - config.queue.push( callback ); - - if ( config.autorun && !config.blocking ) { - process( last ); - } -} - -function process( last ) { - function next() { - process( last ); - } - var start = now(); - config.depth = ( config.depth || 0 ) + 1; - - while ( config.queue.length && !config.blocking ) { - if ( !defined.setTimeout || config.updateRate <= 0 || - ( ( now() - start ) < config.updateRate ) ) { - if ( config.current ) { - - // Reset async tracking for each phase of the Test lifecycle - config.current.usedAsync = false; - } - config.queue.shift()(); - } else { - setTimeout( next, 13 ); - break; - } - } - config.depth--; - if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) { - done(); - } -} - -function begin() { - var i, l, - modulesLog = []; - - // If the test run hasn't officially begun yet - if ( !config.started ) { - - // Record the time of the test run's beginning - config.started = now(); - - verifyLoggingCallbacks(); - - // Delete the loose unnamed module if unused. - if ( config.modules[ 0 ].name === "" && config.modules[ 0 ].tests.length === 0 ) { - config.modules.shift(); - } - - // Avoid unnecessary information by not logging modules' test environments - for ( i = 0, l = config.modules.length; i < l; i++ ) { - modulesLog.push({ - name: config.modules[ i ].name, - tests: config.modules[ i ].tests - }); - } - - // The test run is officially beginning now - runLoggingCallbacks( "begin", { - totalTests: Test.count, - modules: modulesLog - }); - } - - config.blocking = false; - process( true ); -} - -function resumeProcessing() { - runStarted = true; - - // A slight delay to allow this iteration of the event loop to finish (more assertions, etc.) - if ( defined.setTimeout ) { - setTimeout(function() { - if ( config.current && config.current.semaphore > 0 ) { - return; - } - if ( config.timeout ) { - clearTimeout( config.timeout ); - } - - begin(); - }, 13 ); - } else { - begin(); - } -} - -function pauseProcessing() { - config.blocking = true; - - if ( config.testTimeout && defined.setTimeout ) { - clearTimeout( config.timeout ); - config.timeout = setTimeout(function() { - if ( config.current ) { - config.current.semaphore = 0; - QUnit.pushFailure( "Test timed out", sourceFromStacktrace( 2 ) ); - } else { - throw new Error( "Test timed out" ); - } - resumeProcessing(); - }, config.testTimeout ); - } -} - -function saveGlobal() { - config.pollution = []; - - if ( config.noglobals ) { - for ( var key in window ) { - if ( hasOwn.call( window, key ) ) { - // in Opera sometimes DOM element ids show up here, ignore them - if ( /^qunit-test-output/.test( key ) ) { - continue; - } - config.pollution.push( key ); - } - } - } -} - -function checkPollution() { - var newGlobals, - deletedGlobals, - old = config.pollution; - - saveGlobal(); - - newGlobals = diff( config.pollution, old ); - if ( newGlobals.length > 0 ) { - QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join( ", " ) ); - } - - deletedGlobals = diff( old, config.pollution ); - if ( deletedGlobals.length > 0 ) { - QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join( ", " ) ); - } -} - -// returns a new Array with the elements that are in a but not in b -function diff( a, b ) { - var i, j, - result = a.slice(); - - for ( i = 0; i < result.length; i++ ) { - for ( j = 0; j < b.length; j++ ) { - if ( result[ i ] === b[ j ] ) { - result.splice( i, 1 ); - i--; - break; - } - } - } - return result; -} - -function extend( a, b, undefOnly ) { - for ( var prop in b ) { - if ( hasOwn.call( b, prop ) ) { - - // Avoid "Member not found" error in IE8 caused by messing with window.constructor - if ( !( prop === "constructor" && a === window ) ) { - if ( b[ prop ] === undefined ) { - delete a[ prop ]; - } else if ( !( undefOnly && typeof a[ prop ] !== "undefined" ) ) { - a[ prop ] = b[ prop ]; - } - } - } - } - - return a; -} - -function runLoggingCallbacks( key, args ) { - var i, l, callbacks; - - callbacks = config.callbacks[ key ]; - for ( i = 0, l = callbacks.length; i < l; i++ ) { - callbacks[ i ]( args ); - } -} - -// DEPRECATED: This will be removed on 2.0.0+ -// This function verifies if the loggingCallbacks were modified by the user -// If so, it will restore it, assign the given callback and print a console warning -function verifyLoggingCallbacks() { - var loggingCallback, userCallback; - - for ( loggingCallback in loggingCallbacks ) { - if ( QUnit[ loggingCallback ] !== loggingCallbacks[ loggingCallback ] ) { - - userCallback = QUnit[ loggingCallback ]; - - // Restore the callback function - QUnit[ loggingCallback ] = loggingCallbacks[ loggingCallback ]; - - // Assign the deprecated given callback - QUnit[ loggingCallback ]( userCallback ); - - if ( window.console && window.console.warn ) { - window.console.warn( - "QUnit." + loggingCallback + " was replaced with a new value.\n" + - "Please, check out the documentation on how to apply logging callbacks.\n" + - "Reference: http://api.qunitjs.com/category/callbacks/" - ); - } - } - } -} - -// from jquery.js -function inArray( elem, array ) { - if ( array.indexOf ) { - return array.indexOf( elem ); - } - - for ( var i = 0, length = array.length; i < length; i++ ) { - if ( array[ i ] === elem ) { - return i; - } - } - - return -1; -} - -function Test( settings ) { - var i, l; - - ++Test.count; - - extend( this, settings ); - this.assertions = []; - this.semaphore = 0; - this.usedAsync = false; - this.module = config.currentModule; - this.stack = sourceFromStacktrace( 3 ); - - // Register unique strings - for ( i = 0, l = this.module.tests; i < l.length; i++ ) { - if ( this.module.tests[ i ].name === this.testName ) { - this.testName += " "; - } - } - - this.testId = generateHash( this.module.name, this.testName ); - - this.module.tests.push({ - name: this.testName, - testId: this.testId - }); - - if ( settings.skip ) { - - // Skipped tests will fully ignore any sent callback - this.callback = function() {}; - this.async = false; - this.expected = 0; - } else { - this.assert = new Assert( this ); - } -} - -Test.count = 0; - -Test.prototype = { - before: function() { - if ( - - // Emit moduleStart when we're switching from one module to another - this.module !== config.previousModule || - - // They could be equal (both undefined) but if the previousModule property doesn't - // yet exist it means this is the first test in a suite that isn't wrapped in a - // module, in which case we'll just emit a moduleStart event for 'undefined'. - // Without this, reporters can get testStart before moduleStart which is a problem. - !hasOwn.call( config, "previousModule" ) - ) { - if ( hasOwn.call( config, "previousModule" ) ) { - runLoggingCallbacks( "moduleDone", { - name: config.previousModule.name, - tests: config.previousModule.tests, - failed: config.moduleStats.bad, - passed: config.moduleStats.all - config.moduleStats.bad, - total: config.moduleStats.all, - runtime: now() - config.moduleStats.started - }); - } - config.previousModule = this.module; - config.moduleStats = { all: 0, bad: 0, started: now() }; - runLoggingCallbacks( "moduleStart", { - name: this.module.name, - tests: this.module.tests - }); - } - - config.current = this; - - this.testEnvironment = extend( {}, this.module.testEnvironment ); - delete this.testEnvironment.beforeEach; - delete this.testEnvironment.afterEach; - - this.started = now(); - runLoggingCallbacks( "testStart", { - name: this.testName, - module: this.module.name, - testId: this.testId - }); - - if ( !config.pollution ) { - saveGlobal(); - } - }, - - run: function() { - var promise; - - config.current = this; - - if ( this.async ) { - QUnit.stop(); - } - - this.callbackStarted = now(); - - if ( config.notrycatch ) { - promise = this.callback.call( this.testEnvironment, this.assert ); - this.resolvePromise( promise ); - return; - } - - try { - promise = this.callback.call( this.testEnvironment, this.assert ); - this.resolvePromise( promise ); - } catch ( e ) { - this.pushFailure( "Died on test #" + ( this.assertions.length + 1 ) + " " + - this.stack + ": " + ( e.message || e ), extractStacktrace( e, 0 ) ); - - // else next test will carry the responsibility - saveGlobal(); - - // Restart the tests if they're blocking - if ( config.blocking ) { - QUnit.start(); - } - } - }, - - after: function() { - checkPollution(); - }, - - queueHook: function( hook, hookName ) { - var promise, - test = this; - return function runHook() { - config.current = test; - if ( config.notrycatch ) { - promise = hook.call( test.testEnvironment, test.assert ); - test.resolvePromise( promise, hookName ); - return; - } - try { - promise = hook.call( test.testEnvironment, test.assert ); - test.resolvePromise( promise, hookName ); - } catch ( error ) { - test.pushFailure( hookName + " failed on " + test.testName + ": " + - ( error.message || error ), extractStacktrace( error, 0 ) ); - } - }; - }, - - // Currently only used for module level hooks, can be used to add global level ones - hooks: function( handler ) { - var hooks = []; - - // Hooks are ignored on skipped tests - if ( this.skip ) { - return hooks; - } - - if ( this.module.testEnvironment && - QUnit.objectType( this.module.testEnvironment[ handler ] ) === "function" ) { - hooks.push( this.queueHook( this.module.testEnvironment[ handler ], handler ) ); - } - - return hooks; - }, - - finish: function() { - config.current = this; - if ( config.requireExpects && this.expected === null ) { - this.pushFailure( "Expected number of assertions to be defined, but expect() was " + - "not called.", this.stack ); - } else if ( this.expected !== null && this.expected !== this.assertions.length ) { - this.pushFailure( "Expected " + this.expected + " assertions, but " + - this.assertions.length + " were run", this.stack ); - } else if ( this.expected === null && !this.assertions.length ) { - this.pushFailure( "Expected at least one assertion, but none were run - call " + - "expect(0) to accept zero assertions.", this.stack ); - } - - var i, - bad = 0; - - this.runtime = now() - this.started; - config.stats.all += this.assertions.length; - config.moduleStats.all += this.assertions.length; - - for ( i = 0; i < this.assertions.length; i++ ) { - if ( !this.assertions[ i ].result ) { - bad++; - config.stats.bad++; - config.moduleStats.bad++; - } - } - - runLoggingCallbacks( "testDone", { - name: this.testName, - module: this.module.name, - skipped: !!this.skip, - failed: bad, - passed: this.assertions.length - bad, - total: this.assertions.length, - runtime: this.runtime, - - // HTML Reporter use - assertions: this.assertions, - testId: this.testId, - - // DEPRECATED: this property will be removed in 2.0.0, use runtime instead - duration: this.runtime - }); - - // QUnit.reset() is deprecated and will be replaced for a new - // fixture reset function on QUnit 2.0/2.1. - // It's still called here for backwards compatibility handling - QUnit.reset(); - - config.current = undefined; - }, - - queue: function() { - var bad, - test = this; - - if ( !this.valid() ) { - return; - } - - function run() { - - // each of these can by async - synchronize([ - function() { - test.before(); - }, - - test.hooks( "beforeEach" ), - - function() { - test.run(); - }, - - test.hooks( "afterEach" ).reverse(), - - function() { - test.after(); - }, - function() { - test.finish(); - } - ]); - } - - // `bad` initialized at top of scope - // defer when previous test run passed, if storage is available - bad = QUnit.config.reorder && defined.sessionStorage && - +sessionStorage.getItem( "qunit-test-" + this.module.name + "-" + this.testName ); - - if ( bad ) { - run(); - } else { - synchronize( run, true ); - } - }, - - push: function( result, actual, expected, message ) { - var source, - details = { - module: this.module.name, - name: this.testName, - result: result, - message: message, - actual: actual, - expected: expected, - testId: this.testId, - runtime: now() - this.started - }; - - if ( !result ) { - source = sourceFromStacktrace(); - - if ( source ) { - details.source = source; - } - } - - runLoggingCallbacks( "log", details ); - - this.assertions.push({ - result: !!result, - message: message - }); - }, - - pushFailure: function( message, source, actual ) { - if ( !this instanceof Test ) { - throw new Error( "pushFailure() assertion outside test context, was " + - sourceFromStacktrace( 2 ) ); - } - - var details = { - module: this.module.name, - name: this.testName, - result: false, - message: message || "error", - actual: actual || null, - testId: this.testId, - runtime: now() - this.started - }; - - if ( source ) { - details.source = source; - } - - runLoggingCallbacks( "log", details ); - - this.assertions.push({ - result: false, - message: message - }); - }, - - resolvePromise: function( promise, phase ) { - var then, message, - test = this; - if ( promise != null ) { - then = promise.then; - if ( QUnit.objectType( then ) === "function" ) { - QUnit.stop(); - then.call( - promise, - QUnit.start, - function( error ) { - message = "Promise rejected " + - ( !phase ? "during" : phase.replace( /Each$/, "" ) ) + - " " + test.testName + ": " + ( error.message || error ); - test.pushFailure( message, extractStacktrace( error, 0 ) ); - - // else next test will carry the responsibility - saveGlobal(); - - // Unblock - QUnit.start(); - } - ); - } - } - }, - - valid: function() { - var include, - filter = config.filter, - module = QUnit.urlParams.module && QUnit.urlParams.module.toLowerCase(), - fullName = ( this.module.name + ": " + this.testName ).toLowerCase(); - - // Internally-generated tests are always valid - if ( this.callback && this.callback.validTest ) { - return true; - } - - if ( config.testId.length > 0 && inArray( this.testId, config.testId ) < 0 ) { - return false; - } - - if ( module && ( !this.module.name || this.module.name.toLowerCase() !== module ) ) { - return false; - } - - if ( !filter ) { - return true; - } - - include = filter.charAt( 0 ) !== "!"; - if ( !include ) { - filter = filter.toLowerCase().slice( 1 ); - } - - // If the filter matches, we need to honour include - if ( fullName.indexOf( filter ) !== -1 ) { - return include; - } - - // Otherwise, do the opposite - return !include; - } - -}; - -// Resets the test setup. Useful for tests that modify the DOM. -/* -DEPRECATED: Use multiple tests instead of resetting inside a test. -Use testStart or testDone for custom cleanup. -This method will throw an error in 2.0, and will be removed in 2.1 -*/ -QUnit.reset = function() { - - // Return on non-browser environments - // This is necessary to not break on node tests - if ( typeof window === "undefined" ) { - return; - } - - var fixture = defined.document && document.getElementById && - document.getElementById( "qunit-fixture" ); - - if ( fixture ) { - fixture.innerHTML = config.fixture; - } -}; - -QUnit.pushFailure = function() { - if ( !QUnit.config.current ) { - throw new Error( "pushFailure() assertion outside test context, in " + - sourceFromStacktrace( 2 ) ); - } - - // Gets current test obj - var currentTest = QUnit.config.current; - - return currentTest.pushFailure.apply( currentTest, arguments ); -}; - -// Based on Java's String.hashCode, a simple but not -// rigorously collision resistant hashing function -function generateHash( module, testName ) { - var hex, - i = 0, - hash = 0, - str = module + "\x1C" + testName, - len = str.length; - - for ( ; i < len; i++ ) { - hash = ( ( hash << 5 ) - hash ) + str.charCodeAt( i ); - hash |= 0; - } - - // Convert the possibly negative integer hash code into an 8 character hex string, which isn't - // strictly necessary but increases user understanding that the id is a SHA-like hash - hex = ( 0x100000000 + hash ).toString( 16 ); - if ( hex.length < 8 ) { - hex = "0000000" + hex; - } - - return hex.slice( -8 ); -} - -function Assert( testContext ) { - this.test = testContext; -} - -// Assert helpers -QUnit.assert = Assert.prototype = { - - // Specify the number of expected assertions to guarantee that failed test - // (no assertions are run at all) don't slip through. - expect: function( asserts ) { - if ( arguments.length === 1 ) { - this.test.expected = asserts; - } else { - return this.test.expected; - } - }, - - // Increment this Test's semaphore counter, then return a single-use function that - // decrements that counter a maximum of once. - async: function() { - var test = this.test, - popped = false; - - test.semaphore += 1; - test.usedAsync = true; - pauseProcessing(); - - return function done() { - if ( !popped ) { - test.semaphore -= 1; - popped = true; - resumeProcessing(); - } else { - test.pushFailure( "Called the callback returned from `assert.async` more than once", - sourceFromStacktrace( 2 ) ); - } - }; - }, - - // Exports test.push() to the user API - push: function( /* result, actual, expected, message */ ) { - var assert = this, - currentTest = ( assert instanceof Assert && assert.test ) || QUnit.config.current; - - // Backwards compatibility fix. - // Allows the direct use of global exported assertions and QUnit.assert.* - // Although, it's use is not recommended as it can leak assertions - // to other tests from async tests, because we only get a reference to the current test, - // not exactly the test where assertion were intended to be called. - if ( !currentTest ) { - throw new Error( "assertion outside test context, in " + sourceFromStacktrace( 2 ) ); - } - - if ( currentTest.usedAsync === true && currentTest.semaphore === 0 ) { - currentTest.pushFailure( "Assertion after the final `assert.async` was resolved", - sourceFromStacktrace( 2 ) ); - - // Allow this assertion to continue running anyway... - } - - if ( !( assert instanceof Assert ) ) { - assert = currentTest.assert; - } - return assert.test.push.apply( assert.test, arguments ); - }, - - /** - * Asserts rough true-ish result. - * @name ok - * @function - * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); - */ - ok: function( result, message ) { - message = message || ( result ? "okay" : "failed, expected argument to be truthy, was: " + - QUnit.dump.parse( result ) ); - this.push( !!result, result, true, message ); - }, - - /** - * Assert that the first two arguments are equal, with an optional message. - * Prints out both actual and expected values. - * @name equal - * @function - * @example equal( format( "{0} bytes.", 2), "2 bytes.", "replaces {0} with next argument" ); - */ - equal: function( actual, expected, message ) { - /*jshint eqeqeq:false */ - this.push( expected == actual, actual, expected, message ); - }, - - /** - * @name notEqual - * @function - */ - notEqual: function( actual, expected, message ) { - /*jshint eqeqeq:false */ - this.push( expected != actual, actual, expected, message ); - }, - - /** - * @name propEqual - * @function - */ - propEqual: function( actual, expected, message ) { - actual = objectValues( actual ); - expected = objectValues( expected ); - this.push( QUnit.equiv( actual, expected ), actual, expected, message ); - }, - - /** - * @name notPropEqual - * @function - */ - notPropEqual: function( actual, expected, message ) { - actual = objectValues( actual ); - expected = objectValues( expected ); - this.push( !QUnit.equiv( actual, expected ), actual, expected, message ); - }, - - /** - * @name deepEqual - * @function - */ - deepEqual: function( actual, expected, message ) { - this.push( QUnit.equiv( actual, expected ), actual, expected, message ); - }, - - /** - * @name notDeepEqual - * @function - */ - notDeepEqual: function( actual, expected, message ) { - this.push( !QUnit.equiv( actual, expected ), actual, expected, message ); - }, - - /** - * @name strictEqual - * @function - */ - strictEqual: function( actual, expected, message ) { - this.push( expected === actual, actual, expected, message ); - }, - - /** - * @name notStrictEqual - * @function - */ - notStrictEqual: function( actual, expected, message ) { - this.push( expected !== actual, actual, expected, message ); - }, - - "throws": function( block, expected, message ) { - var actual, expectedType, - expectedOutput = expected, - ok = false; - - // 'expected' is optional unless doing string comparison - if ( message == null && typeof expected === "string" ) { - message = expected; - expected = null; - } - - this.test.ignoreGlobalErrors = true; - try { - block.call( this.test.testEnvironment ); - } catch (e) { - actual = e; - } - this.test.ignoreGlobalErrors = false; - - if ( actual ) { - expectedType = QUnit.objectType( expected ); - - // we don't want to validate thrown error - if ( !expected ) { - ok = true; - expectedOutput = null; - - // expected is a regexp - } else if ( expectedType === "regexp" ) { - ok = expected.test( errorString( actual ) ); - - // expected is a string - } else if ( expectedType === "string" ) { - ok = expected === errorString( actual ); - - // expected is a constructor, maybe an Error constructor - } else if ( expectedType === "function" && actual instanceof expected ) { - ok = true; - - // expected is an Error object - } else if ( expectedType === "object" ) { - ok = actual instanceof expected.constructor && - actual.name === expected.name && - actual.message === expected.message; - - // expected is a validation function which returns true if validation passed - } else if ( expectedType === "function" && expected.call( {}, actual ) === true ) { - expectedOutput = null; - ok = true; - } - - this.push( ok, actual, expectedOutput, message ); - } else { - this.test.pushFailure( message, null, "No exception was thrown." ); - } - } -}; - -// Provide an alternative to assert.throws(), for enviroments that consider throws a reserved word -// Known to us are: Closure Compiler, Narwhal -(function() { - /*jshint sub:true */ - Assert.prototype.raises = Assert.prototype[ "throws" ]; -}()); - -// Test for equality any JavaScript type. -// Author: Philippe Rathé -QUnit.equiv = (function() { - - // Call the o related callback with the given arguments. - function bindCallbacks( o, callbacks, args ) { - var prop = QUnit.objectType( o ); - if ( prop ) { - if ( QUnit.objectType( callbacks[ prop ] ) === "function" ) { - return callbacks[ prop ].apply( callbacks, args ); - } else { - return callbacks[ prop ]; // or undefined - } - } - } - - // the real equiv function - var innerEquiv, - - // stack to decide between skip/abort functions - callers = [], - - // stack to avoiding loops from circular referencing - parents = [], - parentsB = [], - - getProto = Object.getPrototypeOf || function( obj ) { - /* jshint camelcase: false, proto: true */ - return obj.__proto__; - }, - callbacks = (function() { - - // for string, boolean, number and null - function useStrictEquality( b, a ) { - - /*jshint eqeqeq:false */ - if ( b instanceof a.constructor || a instanceof b.constructor ) { - - // to catch short annotation VS 'new' annotation of a - // declaration - // e.g. var i = 1; - // var j = new Number(1); - return a == b; - } else { - return a === b; - } - } - - return { - "string": useStrictEquality, - "boolean": useStrictEquality, - "number": useStrictEquality, - "null": useStrictEquality, - "undefined": useStrictEquality, - - "nan": function( b ) { - return isNaN( b ); - }, - - "date": function( b, a ) { - return QUnit.objectType( b ) === "date" && a.valueOf() === b.valueOf(); - }, - - "regexp": function( b, a ) { - return QUnit.objectType( b ) === "regexp" && - - // the regex itself - a.source === b.source && - - // and its modifiers - a.global === b.global && - - // (gmi) ... - a.ignoreCase === b.ignoreCase && - a.multiline === b.multiline && - a.sticky === b.sticky; - }, - - // - skip when the property is a method of an instance (OOP) - // - abort otherwise, - // initial === would have catch identical references anyway - "function": function() { - var caller = callers[ callers.length - 1 ]; - return caller !== Object && typeof caller !== "undefined"; - }, - - "array": function( b, a ) { - var i, j, len, loop, aCircular, bCircular; - - // b could be an object literal here - if ( QUnit.objectType( b ) !== "array" ) { - return false; - } - - len = a.length; - if ( len !== b.length ) { - // safe and faster - return false; - } - - // track reference to avoid circular references - parents.push( a ); - parentsB.push( b ); - for ( i = 0; i < len; i++ ) { - loop = false; - for ( j = 0; j < parents.length; j++ ) { - aCircular = parents[ j ] === a[ i ]; - bCircular = parentsB[ j ] === b[ i ]; - if ( aCircular || bCircular ) { - if ( a[ i ] === b[ i ] || aCircular && bCircular ) { - loop = true; - } else { - parents.pop(); - parentsB.pop(); - return false; - } - } - } - if ( !loop && !innerEquiv( a[ i ], b[ i ] ) ) { - parents.pop(); - parentsB.pop(); - return false; - } - } - parents.pop(); - parentsB.pop(); - return true; - }, - - "object": function( b, a ) { - - /*jshint forin:false */ - var i, j, loop, aCircular, bCircular, - // Default to true - eq = true, - aProperties = [], - bProperties = []; - - // comparing constructors is more strict than using - // instanceof - if ( a.constructor !== b.constructor ) { - - // Allow objects with no prototype to be equivalent to - // objects with Object as their constructor. - if ( !( ( getProto( a ) === null && getProto( b ) === Object.prototype ) || - ( getProto( b ) === null && getProto( a ) === Object.prototype ) ) ) { - return false; - } - } - - // stack constructor before traversing properties - callers.push( a.constructor ); - - // track reference to avoid circular references - parents.push( a ); - parentsB.push( b ); - - // be strict: don't ensure hasOwnProperty and go deep - for ( i in a ) { - loop = false; - for ( j = 0; j < parents.length; j++ ) { - aCircular = parents[ j ] === a[ i ]; - bCircular = parentsB[ j ] === b[ i ]; - if ( aCircular || bCircular ) { - if ( a[ i ] === b[ i ] || aCircular && bCircular ) { - loop = true; - } else { - eq = false; - break; - } - } - } - aProperties.push( i ); - if ( !loop && !innerEquiv( a[ i ], b[ i ] ) ) { - eq = false; - break; - } - } - - parents.pop(); - parentsB.pop(); - callers.pop(); // unstack, we are done - - for ( i in b ) { - bProperties.push( i ); // collect b's properties - } - - // Ensures identical properties name - return eq && innerEquiv( aProperties.sort(), bProperties.sort() ); - } - }; - }()); - - innerEquiv = function() { // can take multiple arguments - var args = [].slice.apply( arguments ); - if ( args.length < 2 ) { - return true; // end transition - } - - return ( (function( a, b ) { - if ( a === b ) { - return true; // catch the most you can - } else if ( a === null || b === null || typeof a === "undefined" || - typeof b === "undefined" || - QUnit.objectType( a ) !== QUnit.objectType( b ) ) { - - // don't lose time with error prone cases - return false; - } else { - return bindCallbacks( a, callbacks, [ b, a ] ); - } - - // apply transition with (1..n) arguments - }( args[ 0 ], args[ 1 ] ) ) && - innerEquiv.apply( this, args.splice( 1, args.length - 1 ) ) ); - }; - - return innerEquiv; -}()); - -// Based on jsDump by Ariel Flesler -// http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html -QUnit.dump = (function() { - function quote( str ) { - return "\"" + str.toString().replace( /"/g, "\\\"" ) + "\""; - } - function literal( o ) { - return o + ""; - } - function join( pre, arr, post ) { - var s = dump.separator(), - base = dump.indent(), - inner = dump.indent( 1 ); - if ( arr.join ) { - arr = arr.join( "," + s + inner ); - } - if ( !arr ) { - return pre + post; - } - return [ pre, inner + arr, base + post ].join( s ); - } - function array( arr, stack ) { - var i = arr.length, - ret = new Array( i ); - - if ( dump.maxDepth && dump.depth > dump.maxDepth ) { - return "[object Array]"; - } - - this.up(); - while ( i-- ) { - ret[ i ] = this.parse( arr[ i ], undefined, stack ); - } - this.down(); - return join( "[", ret, "]" ); - } - - var reName = /^function (\w+)/, - dump = { - - // objType is used mostly internally, you can fix a (custom) type in advance - parse: function( obj, objType, stack ) { - stack = stack || []; - var res, parser, parserType, - inStack = inArray( obj, stack ); - - if ( inStack !== -1 ) { - return "recursion(" + ( inStack - stack.length ) + ")"; - } - - objType = objType || this.typeOf( obj ); - parser = this.parsers[ objType ]; - parserType = typeof parser; - - if ( parserType === "function" ) { - stack.push( obj ); - res = parser.call( this, obj, stack ); - stack.pop(); - return res; - } - return ( parserType === "string" ) ? parser : this.parsers.error; - }, - typeOf: function( obj ) { - var type; - if ( obj === null ) { - type = "null"; - } else if ( typeof obj === "undefined" ) { - type = "undefined"; - } else if ( QUnit.is( "regexp", obj ) ) { - type = "regexp"; - } else if ( QUnit.is( "date", obj ) ) { - type = "date"; - } else if ( QUnit.is( "function", obj ) ) { - type = "function"; - } else if ( obj.setInterval !== undefined && - obj.document !== undefined && - obj.nodeType === undefined ) { - type = "window"; - } else if ( obj.nodeType === 9 ) { - type = "document"; - } else if ( obj.nodeType ) { - type = "node"; - } else if ( - - // native arrays - toString.call( obj ) === "[object Array]" || - - // NodeList objects - ( typeof obj.length === "number" && obj.item !== undefined && - ( obj.length ? obj.item( 0 ) === obj[ 0 ] : ( obj.item( 0 ) === null && - obj[ 0 ] === undefined ) ) ) - ) { - type = "array"; - } else if ( obj.constructor === Error.prototype.constructor ) { - type = "error"; - } else { - type = typeof obj; - } - return type; - }, - separator: function() { - return this.multiline ? this.HTML ? "
            " : "\n" : this.HTML ? " " : " "; - }, - // extra can be a number, shortcut for increasing-calling-decreasing - indent: function( extra ) { - if ( !this.multiline ) { - return ""; - } - var chr = this.indentChar; - if ( this.HTML ) { - chr = chr.replace( /\t/g, " " ).replace( / /g, " " ); - } - return new Array( this.depth + ( extra || 0 ) ).join( chr ); - }, - up: function( a ) { - this.depth += a || 1; - }, - down: function( a ) { - this.depth -= a || 1; - }, - setParser: function( name, parser ) { - this.parsers[ name ] = parser; - }, - // The next 3 are exposed so you can use them - quote: quote, - literal: literal, - join: join, - // - depth: 1, - maxDepth: 5, - - // This is the list of parsers, to modify them, use dump.setParser - parsers: { - window: "[Window]", - document: "[Document]", - error: function( error ) { - return "Error(\"" + error.message + "\")"; - }, - unknown: "[Unknown]", - "null": "null", - "undefined": "undefined", - "function": function( fn ) { - var ret = "function", - - // functions never have name in IE - name = "name" in fn ? fn.name : ( reName.exec( fn ) || [] )[ 1 ]; - - if ( name ) { - ret += " " + name; - } - ret += "( "; - - ret = [ ret, dump.parse( fn, "functionArgs" ), "){" ].join( "" ); - return join( ret, dump.parse( fn, "functionCode" ), "}" ); - }, - array: array, - nodelist: array, - "arguments": array, - object: function( map, stack ) { - var keys, key, val, i, nonEnumerableProperties, - ret = []; - - if ( dump.maxDepth && dump.depth > dump.maxDepth ) { - return "[object Object]"; - } - - dump.up(); - keys = []; - for ( key in map ) { - keys.push( key ); - } - - // Some properties are not always enumerable on Error objects. - nonEnumerableProperties = [ "message", "name" ]; - for ( i in nonEnumerableProperties ) { - key = nonEnumerableProperties[ i ]; - if ( key in map && !( key in keys ) ) { - keys.push( key ); - } - } - keys.sort(); - for ( i = 0; i < keys.length; i++ ) { - key = keys[ i ]; - val = map[ key ]; - ret.push( dump.parse( key, "key" ) + ": " + - dump.parse( val, undefined, stack ) ); - } - dump.down(); - return join( "{", ret, "}" ); - }, - node: function( node ) { - var len, i, val, - open = dump.HTML ? "<" : "<", - close = dump.HTML ? ">" : ">", - tag = node.nodeName.toLowerCase(), - ret = open + tag, - attrs = node.attributes; - - if ( attrs ) { - for ( i = 0, len = attrs.length; i < len; i++ ) { - val = attrs[ i ].nodeValue; - - // IE6 includes all attributes in .attributes, even ones not explicitly - // set. Those have values like undefined, null, 0, false, "" or - // "inherit". - if ( val && val !== "inherit" ) { - ret += " " + attrs[ i ].nodeName + "=" + - dump.parse( val, "attribute" ); - } - } - } - ret += close; - - // Show content of TextNode or CDATASection - if ( node.nodeType === 3 || node.nodeType === 4 ) { - ret += node.nodeValue; - } - - return ret + open + "/" + tag + close; - }, - - // function calls it internally, it's the arguments part of the function - functionArgs: function( fn ) { - var args, - l = fn.length; - - if ( !l ) { - return ""; - } - - args = new Array( l ); - while ( l-- ) { - - // 97 is 'a' - args[ l ] = String.fromCharCode( 97 + l ); - } - return " " + args.join( ", " ) + " "; - }, - // object calls it internally, the key part of an item in a map - key: quote, - // function calls it internally, it's the content of the function - functionCode: "[code]", - // node calls it internally, it's an html attribute value - attribute: quote, - string: quote, - date: quote, - regexp: literal, - number: literal, - "boolean": literal - }, - // if true, entities are escaped ( <, >, \t, space and \n ) - HTML: false, - // indentation unit - indentChar: " ", - // if true, items in a collection, are separated by a \n, else just a space. - multiline: true - }; - - return dump; -}()); - -// back compat -QUnit.jsDump = QUnit.dump; - -// For browser, export only select globals -if ( typeof window !== "undefined" ) { - - // Deprecated - // Extend assert methods to QUnit and Global scope through Backwards compatibility - (function() { - var i, - assertions = Assert.prototype; - - function applyCurrent( current ) { - return function() { - var assert = new Assert( QUnit.config.current ); - current.apply( assert, arguments ); - }; - } - - for ( i in assertions ) { - QUnit[ i ] = applyCurrent( assertions[ i ] ); - } - })(); - - (function() { - var i, l, - keys = [ - "test", - "module", - "expect", - "asyncTest", - "start", - "stop", - "ok", - "equal", - "notEqual", - "propEqual", - "notPropEqual", - "deepEqual", - "notDeepEqual", - "strictEqual", - "notStrictEqual", - "throws" - ]; - - for ( i = 0, l = keys.length; i < l; i++ ) { - window[ keys[ i ] ] = QUnit[ keys[ i ] ]; - } - })(); - - window.QUnit = QUnit; -} - -// For nodejs -if ( typeof module !== "undefined" && module && module.exports ) { - module.exports = QUnit; - - // For consistency with CommonJS environments' exports - module.exports.QUnit = QUnit; -} - -// For CommonJS with exports, but without module.exports, like Rhino -if ( typeof exports !== "undefined" && exports ) { - exports.QUnit = QUnit; -} - -// Get a reference to the global object, like window in browsers -}( (function() { - return this; -})() )); - -/*istanbul ignore next */ -// jscs:disable maximumLineLength -/* - * Javascript Diff Algorithm - * By John Resig (http://ejohn.org/) - * Modified by Chu Alan "sprite" - * - * Released under the MIT license. - * - * More Info: - * http://ejohn.org/projects/javascript-diff-algorithm/ - * - * Usage: QUnit.diff(expected, actual) - * - * QUnit.diff( "the quick brown fox jumped over", "the quick fox jumps over" ) == "the quick brown fox jumped jumps over" - */ -QUnit.diff = (function() { - var hasOwn = Object.prototype.hasOwnProperty; - - /*jshint eqeqeq:false, eqnull:true */ - function diff( o, n ) { - var i, - ns = {}, - os = {}; - - for ( i = 0; i < n.length; i++ ) { - if ( !hasOwn.call( ns, n[ i ] ) ) { - ns[ n[ i ] ] = { - rows: [], - o: null - }; - } - ns[ n[ i ] ].rows.push( i ); - } - - for ( i = 0; i < o.length; i++ ) { - if ( !hasOwn.call( os, o[ i ] ) ) { - os[ o[ i ] ] = { - rows: [], - n: null - }; - } - os[ o[ i ] ].rows.push( i ); - } - - for ( i in ns ) { - if ( hasOwn.call( ns, i ) ) { - if ( ns[ i ].rows.length === 1 && hasOwn.call( os, i ) && os[ i ].rows.length === 1 ) { - n[ ns[ i ].rows[ 0 ] ] = { - text: n[ ns[ i ].rows[ 0 ] ], - row: os[ i ].rows[ 0 ] - }; - o[ os[ i ].rows[ 0 ] ] = { - text: o[ os[ i ].rows[ 0 ] ], - row: ns[ i ].rows[ 0 ] - }; - } - } - } - - for ( i = 0; i < n.length - 1; i++ ) { - if ( n[ i ].text != null && n[ i + 1 ].text == null && n[ i ].row + 1 < o.length && o[ n[ i ].row + 1 ].text == null && - n[ i + 1 ] == o[ n[ i ].row + 1 ] ) { - - n[ i + 1 ] = { - text: n[ i + 1 ], - row: n[ i ].row + 1 - }; - o[ n[ i ].row + 1 ] = { - text: o[ n[ i ].row + 1 ], - row: i + 1 - }; - } - } - - for ( i = n.length - 1; i > 0; i-- ) { - if ( n[ i ].text != null && n[ i - 1 ].text == null && n[ i ].row > 0 && o[ n[ i ].row - 1 ].text == null && - n[ i - 1 ] == o[ n[ i ].row - 1 ] ) { - - n[ i - 1 ] = { - text: n[ i - 1 ], - row: n[ i ].row - 1 - }; - o[ n[ i ].row - 1 ] = { - text: o[ n[ i ].row - 1 ], - row: i - 1 - }; - } - } - - return { - o: o, - n: n - }; - } - - return function( o, n ) { - o = o.replace( /\s+$/, "" ); - n = n.replace( /\s+$/, "" ); - - var i, pre, - str = "", - out = diff( o === "" ? [] : o.split( /\s+/ ), n === "" ? [] : n.split( /\s+/ ) ), - oSpace = o.match( /\s+/g ), - nSpace = n.match( /\s+/g ); - - if ( oSpace == null ) { - oSpace = [ " " ]; - } else { - oSpace.push( " " ); - } - - if ( nSpace == null ) { - nSpace = [ " " ]; - } else { - nSpace.push( " " ); - } - - if ( out.n.length === 0 ) { - for ( i = 0; i < out.o.length; i++ ) { - str += "" + out.o[ i ] + oSpace[ i ] + ""; - } - } else { - if ( out.n[ 0 ].text == null ) { - for ( n = 0; n < out.o.length && out.o[ n ].text == null; n++ ) { - str += "" + out.o[ n ] + oSpace[ n ] + ""; - } - } - - for ( i = 0; i < out.n.length; i++ ) { - if ( out.n[ i ].text == null ) { - str += "" + out.n[ i ] + nSpace[ i ] + ""; - } else { - - // `pre` initialized at top of scope - pre = ""; - - for ( n = out.n[ i ].row + 1; n < out.o.length && out.o[ n ].text == null; n++ ) { - pre += "" + out.o[ n ] + oSpace[ n ] + ""; - } - str += " " + out.n[ i ].text + nSpace[ i ] + pre; - } - } - } - - return str; - }; -}()); -// jscs:enable - -(function() { - -// Deprecated QUnit.init - Ref #530 -// Re-initialize the configuration options -QUnit.init = function() { - var tests, banner, result, qunit, - config = QUnit.config; - - config.stats = { all: 0, bad: 0 }; - config.moduleStats = { all: 0, bad: 0 }; - config.started = 0; - config.updateRate = 1000; - config.blocking = false; - config.autostart = true; - config.autorun = false; - config.filter = ""; - config.queue = []; - - // Return on non-browser environments - // This is necessary to not break on node tests - if ( typeof window === "undefined" ) { - return; - } - - qunit = id( "qunit" ); - if ( qunit ) { - qunit.innerHTML = - "

            " + escapeText( document.title ) + "

            " + - "

            " + - "
            " + - "

            " + - "
              "; - } - - tests = id( "qunit-tests" ); - banner = id( "qunit-banner" ); - result = id( "qunit-testresult" ); - - if ( tests ) { - tests.innerHTML = ""; - } - - if ( banner ) { - banner.className = ""; - } - - if ( result ) { - result.parentNode.removeChild( result ); - } - - if ( tests ) { - result = document.createElement( "p" ); - result.id = "qunit-testresult"; - result.className = "result"; - tests.parentNode.insertBefore( result, tests ); - result.innerHTML = "Running...
               "; - } -}; - -// Don't load the HTML Reporter on non-Browser environments -if ( typeof window === "undefined" ) { - return; -} - -var config = QUnit.config, - hasOwn = Object.prototype.hasOwnProperty, - defined = { - document: window.document !== undefined, - sessionStorage: (function() { - var x = "qunit-test-string"; - try { - sessionStorage.setItem( x, x ); - sessionStorage.removeItem( x ); - return true; - } catch ( e ) { - return false; - } - }()) - }, - modulesList = []; - -/** -* Escape text for attribute or text content. -*/ -function escapeText( s ) { - if ( !s ) { - return ""; - } - s = s + ""; - - // Both single quotes and double quotes (for attributes) - return s.replace( /['"<>&]/g, function( s ) { - switch ( s ) { - case "'": - return "'"; - case "\"": - return """; - case "<": - return "<"; - case ">": - return ">"; - case "&": - return "&"; - } - }); -} - -/** - * @param {HTMLElement} elem - * @param {string} type - * @param {Function} fn - */ -function addEvent( elem, type, fn ) { - if ( elem.addEventListener ) { - - // Standards-based browsers - elem.addEventListener( type, fn, false ); - } else if ( elem.attachEvent ) { - - // support: IE <9 - elem.attachEvent( "on" + type, fn ); - } -} - -/** - * @param {Array|NodeList} elems - * @param {string} type - * @param {Function} fn - */ -function addEvents( elems, type, fn ) { - var i = elems.length; - while ( i-- ) { - addEvent( elems[ i ], type, fn ); - } -} - -function hasClass( elem, name ) { - return ( " " + elem.className + " " ).indexOf( " " + name + " " ) >= 0; -} - -function addClass( elem, name ) { - if ( !hasClass( elem, name ) ) { - elem.className += ( elem.className ? " " : "" ) + name; - } -} - -function toggleClass( elem, name ) { - if ( hasClass( elem, name ) ) { - removeClass( elem, name ); - } else { - addClass( elem, name ); - } -} - -function removeClass( elem, name ) { - var set = " " + elem.className + " "; - - // Class name may appear multiple times - while ( set.indexOf( " " + name + " " ) >= 0 ) { - set = set.replace( " " + name + " ", " " ); - } - - // trim for prettiness - elem.className = typeof set.trim === "function" ? set.trim() : set.replace( /^\s+|\s+$/g, "" ); -} - -function id( name ) { - return defined.document && document.getElementById && document.getElementById( name ); -} - -function getUrlConfigHtml() { - var i, j, val, - escaped, escapedTooltip, - selection = false, - len = config.urlConfig.length, - urlConfigHtml = ""; - - for ( i = 0; i < len; i++ ) { - val = config.urlConfig[ i ]; - if ( typeof val === "string" ) { - val = { - id: val, - label: val - }; - } - - escaped = escapeText( val.id ); - escapedTooltip = escapeText( val.tooltip ); - - if ( config[ val.id ] === undefined ) { - config[ val.id ] = QUnit.urlParams[ val.id ]; - } - - if ( !val.value || typeof val.value === "string" ) { - urlConfigHtml += ""; - } else { - urlConfigHtml += ""; - } - } - - return urlConfigHtml; -} - -// Handle "click" events on toolbar checkboxes and "change" for select menus. -// Updates the URL with the new state of `config.urlConfig` values. -function toolbarChanged() { - var updatedUrl, value, - field = this, - params = {}; - - // Detect if field is a select menu or a checkbox - if ( "selectedIndex" in field ) { - value = field.options[ field.selectedIndex ].value || undefined; - } else { - value = field.checked ? ( field.defaultValue || true ) : undefined; - } - - params[ field.name ] = value; - updatedUrl = setUrl( params ); - - if ( "hidepassed" === field.name && "replaceState" in window.history ) { - config[ field.name ] = value || false; - if ( value ) { - addClass( id( "qunit-tests" ), "hidepass" ); - } else { - removeClass( id( "qunit-tests" ), "hidepass" ); - } - - // It is not necessary to refresh the whole page - window.history.replaceState( null, "", updatedUrl ); - } else { - window.location = updatedUrl; - } -} - -function setUrl( params ) { - var key, - querystring = "?"; - - params = QUnit.extend( QUnit.extend( {}, QUnit.urlParams ), params ); - - for ( key in params ) { - if ( hasOwn.call( params, key ) ) { - if ( params[ key ] === undefined ) { - continue; - } - querystring += encodeURIComponent( key ); - if ( params[ key ] !== true ) { - querystring += "=" + encodeURIComponent( params[ key ] ); - } - querystring += "&"; - } - } - return location.protocol + "//" + location.host + - location.pathname + querystring.slice( 0, -1 ); -} - -function applyUrlParams() { - var selectBox = id( "qunit-modulefilter" ), - selection = decodeURIComponent( selectBox.options[ selectBox.selectedIndex ].value ), - filter = id( "qunit-filter-input" ).value; - - window.location = setUrl({ - module: ( selection === "" ) ? undefined : selection, - filter: ( filter === "" ) ? undefined : filter, - - // Remove testId filter - testId: undefined - }); -} - -function toolbarUrlConfigContainer() { - var urlConfigContainer = document.createElement( "span" ); - - urlConfigContainer.innerHTML = getUrlConfigHtml(); - addClass( urlConfigContainer, "qunit-url-config" ); - - // For oldIE support: - // * Add handlers to the individual elements instead of the container - // * Use "click" instead of "change" for checkboxes - addEvents( urlConfigContainer.getElementsByTagName( "input" ), "click", toolbarChanged ); - addEvents( urlConfigContainer.getElementsByTagName( "select" ), "change", toolbarChanged ); - - return urlConfigContainer; -} - -function toolbarLooseFilter() { - var filter = document.createElement( "form" ), - label = document.createElement( "label" ), - input = document.createElement( "input" ), - button = document.createElement( "button" ); - - addClass( filter, "qunit-filter" ); - - label.innerHTML = "Filter: "; - - input.type = "text"; - input.value = config.filter || ""; - input.name = "filter"; - input.id = "qunit-filter-input"; - - button.innerHTML = "Go"; - - label.appendChild( input ); - - filter.appendChild( label ); - filter.appendChild( button ); - addEvent( filter, "submit", function( ev ) { - applyUrlParams(); - - if ( ev && ev.preventDefault ) { - ev.preventDefault(); - } - - return false; - }); - - return filter; -} - -function toolbarModuleFilterHtml() { - var i, - moduleFilterHtml = ""; - - if ( !modulesList.length ) { - return false; - } - - modulesList.sort(function( a, b ) { - return a.localeCompare( b ); - }); - - moduleFilterHtml += "" + - ""; - - return moduleFilterHtml; -} - -function toolbarModuleFilter() { - var toolbar = id( "qunit-testrunner-toolbar" ), - moduleFilter = document.createElement( "span" ), - moduleFilterHtml = toolbarModuleFilterHtml(); - - if ( !toolbar || !moduleFilterHtml ) { - return false; - } - - moduleFilter.setAttribute( "id", "qunit-modulefilter-container" ); - moduleFilter.innerHTML = moduleFilterHtml; - - addEvent( moduleFilter.lastChild, "change", applyUrlParams ); - - toolbar.appendChild( moduleFilter ); -} - -function appendToolbar() { - var toolbar = id( "qunit-testrunner-toolbar" ); - - if ( toolbar ) { - toolbar.appendChild( toolbarUrlConfigContainer() ); - toolbar.appendChild( toolbarLooseFilter() ); - } -} - -function appendHeader() { - var header = id( "qunit-header" ); - - if ( header ) { - header.innerHTML = "" + header.innerHTML + " "; - } -} - -function appendBanner() { - var banner = id( "qunit-banner" ); - - if ( banner ) { - banner.className = ""; - } -} - -function appendTestResults() { - var tests = id( "qunit-tests" ), - result = id( "qunit-testresult" ); - - if ( result ) { - result.parentNode.removeChild( result ); - } - - if ( tests ) { - tests.innerHTML = ""; - result = document.createElement( "p" ); - result.id = "qunit-testresult"; - result.className = "result"; - tests.parentNode.insertBefore( result, tests ); - result.innerHTML = "Running...
               "; - } -} - -function storeFixture() { - var fixture = id( "qunit-fixture" ); - if ( fixture ) { - config.fixture = fixture.innerHTML; - } -} - -function appendUserAgent() { - var userAgent = id( "qunit-userAgent" ); - if ( userAgent ) { - userAgent.innerHTML = ""; - userAgent.appendChild( document.createTextNode( navigator.userAgent ) ); - } -} - -function appendTestsList( modules ) { - var i, l, x, z, test, moduleObj; - - for ( i = 0, l = modules.length; i < l; i++ ) { - moduleObj = modules[ i ]; - - if ( moduleObj.name ) { - modulesList.push( moduleObj.name ); - } - - for ( x = 0, z = moduleObj.tests.length; x < z; x++ ) { - test = moduleObj.tests[ x ]; - - appendTest( test.name, test.testId, moduleObj.name ); - } - } -} - -function appendTest( name, testId, moduleName ) { - var title, rerunTrigger, testBlock, assertList, - tests = id( "qunit-tests" ); - - if ( !tests ) { - return; - } - - title = document.createElement( "strong" ); - title.innerHTML = getNameHtml( name, moduleName ); - - rerunTrigger = document.createElement( "a" ); - rerunTrigger.innerHTML = "Rerun"; - rerunTrigger.href = setUrl({ testId: testId }); - - testBlock = document.createElement( "li" ); - testBlock.appendChild( title ); - testBlock.appendChild( rerunTrigger ); - testBlock.id = "qunit-test-output-" + testId; - - assertList = document.createElement( "ol" ); - assertList.className = "qunit-assert-list"; - - testBlock.appendChild( assertList ); - - tests.appendChild( testBlock ); -} - -// HTML Reporter initialization and load -QUnit.begin(function( details ) { - var qunit = id( "qunit" ); - - // Fixture is the only one necessary to run without the #qunit element - storeFixture(); - - if ( qunit ) { - qunit.innerHTML = - "

              " + escapeText( document.title ) + "

              " + - "

              " + - "
              " + - "

              " + - "
                "; - } - - appendHeader(); - appendBanner(); - appendTestResults(); - appendUserAgent(); - appendToolbar(); - appendTestsList( details.modules ); - toolbarModuleFilter(); - - if ( qunit && config.hidepassed ) { - addClass( qunit.lastChild, "hidepass" ); - } -}); - -QUnit.done(function( details ) { - var i, key, - banner = id( "qunit-banner" ), - tests = id( "qunit-tests" ), - html = [ - "Tests completed in ", - details.runtime, - " milliseconds.
                ", - "", - details.passed, - " assertions of ", - details.total, - " passed, ", - details.failed, - " failed." - ].join( "" ); - - if ( banner ) { - banner.className = details.failed ? "qunit-fail" : "qunit-pass"; - } - - if ( tests ) { - id( "qunit-testresult" ).innerHTML = html; - } - - if ( config.altertitle && defined.document && document.title ) { - - // show ✖ for good, ✔ for bad suite result in title - // use escape sequences in case file gets loaded with non-utf-8-charset - document.title = [ - ( details.failed ? "\u2716" : "\u2714" ), - document.title.replace( /^[\u2714\u2716] /i, "" ) - ].join( " " ); - } - - // clear own sessionStorage items if all tests passed - if ( config.reorder && defined.sessionStorage && details.failed === 0 ) { - for ( i = 0; i < sessionStorage.length; i++ ) { - key = sessionStorage.key( i++ ); - if ( key.indexOf( "qunit-test-" ) === 0 ) { - sessionStorage.removeItem( key ); - } - } - } - - // scroll back to top to show results - if ( config.scrolltop && window.scrollTo ) { - window.scrollTo( 0, 0 ); - } -}); - -function getNameHtml( name, module ) { - var nameHtml = ""; - - if ( module ) { - nameHtml = "" + escapeText( module ) + ": "; - } - - nameHtml += "" + escapeText( name ) + ""; - - return nameHtml; -} - -QUnit.testStart(function( details ) { - var running, testBlock; - - testBlock = id( "qunit-test-output-" + details.testId ); - if ( testBlock ) { - testBlock.className = "running"; - } else { - - // Report later registered tests - appendTest( details.name, details.testId, details.module ); - } - - running = id( "qunit-testresult" ); - if ( running ) { - running.innerHTML = "Running:
                " + getNameHtml( details.name, details.module ); - } - -}); - -QUnit.log(function( details ) { - var assertList, assertLi, - message, expected, actual, - testItem = id( "qunit-test-output-" + details.testId ); - - if ( !testItem ) { - return; - } - - message = escapeText( details.message ) || ( details.result ? "okay" : "failed" ); - message = "" + message + ""; - message += "@ " + details.runtime + " ms"; - - // pushFailure doesn't provide details.expected - // when it calls, it's implicit to also not show expected and diff stuff - // Also, we need to check details.expected existence, as it can exist and be undefined - if ( !details.result && hasOwn.call( details, "expected" ) ) { - expected = escapeText( QUnit.dump.parse( details.expected ) ); - actual = escapeText( QUnit.dump.parse( details.actual ) ); - message += ""; - - if ( actual !== expected ) { - message += "" + - ""; - } - - if ( details.source ) { - message += ""; - } - - message += "
                Expected:
                " +
                -			expected +
                -			"
                Result:
                " +
                -				actual + "
                Diff:
                " +
                -				QUnit.diff( expected, actual ) + "
                Source:
                " +
                -				escapeText( details.source ) + "
                "; - - // this occours when pushFailure is set and we have an extracted stack trace - } else if ( !details.result && details.source ) { - message += "" + - "" + - "
                Source:
                " +
                -			escapeText( details.source ) + "
                "; - } - - assertList = testItem.getElementsByTagName( "ol" )[ 0 ]; - - assertLi = document.createElement( "li" ); - assertLi.className = details.result ? "pass" : "fail"; - assertLi.innerHTML = message; - assertList.appendChild( assertLi ); -}); - -QUnit.testDone(function( details ) { - var testTitle, time, testItem, assertList, - good, bad, testCounts, skipped, - tests = id( "qunit-tests" ); - - if ( !tests ) { - return; - } - - testItem = id( "qunit-test-output-" + details.testId ); - - assertList = testItem.getElementsByTagName( "ol" )[ 0 ]; - - good = details.passed; - bad = details.failed; - - // store result when possible - if ( config.reorder && defined.sessionStorage ) { - if ( bad ) { - sessionStorage.setItem( "qunit-test-" + details.module + "-" + details.name, bad ); - } else { - sessionStorage.removeItem( "qunit-test-" + details.module + "-" + details.name ); - } - } - - if ( bad === 0 ) { - addClass( assertList, "qunit-collapsed" ); - } - - // testItem.firstChild is the test name - testTitle = testItem.firstChild; - - testCounts = bad ? - "" + bad + ", " + "" + good + ", " : - ""; - - testTitle.innerHTML += " (" + testCounts + - details.assertions.length + ")"; - - if ( details.skipped ) { - testItem.className = "skipped"; - skipped = document.createElement( "em" ); - skipped.className = "qunit-skipped-label"; - skipped.innerHTML = "skipped"; - testItem.insertBefore( skipped, testTitle ); - } else { - addEvent( testTitle, "click", function() { - toggleClass( assertList, "qunit-collapsed" ); - }); - - testItem.className = bad ? "fail" : "pass"; - - time = document.createElement( "span" ); - time.className = "runtime"; - time.innerHTML = details.runtime + " ms"; - testItem.insertBefore( time, assertList ); - } -}); - -if ( !defined.document || document.readyState === "complete" ) { - config.pageLoaded = true; - config.autorun = true; -} - -if ( defined.document ) { - addEvent( window, "load", QUnit.load ); -} - -})(); diff --git a/test/lib/qunit-1.17.1.css b/test/lib/qunit-2.9.2.css similarity index 56% rename from test/lib/qunit-1.17.1.css rename to test/lib/qunit-2.9.2.css index 0eb0b017..1f545936 100644 --- a/test/lib/qunit-1.17.1.css +++ b/test/lib/qunit-2.9.2.css @@ -1,33 +1,33 @@ /*! - * QUnit 1.17.1 - * http://qunitjs.com/ + * QUnit 2.9.2 + * https://qunitjs.com/ * * Copyright jQuery Foundation and other contributors * Released under the MIT license - * http://jquery.org/license + * https://jquery.org/license * - * Date: 2015-01-20T19:39Z + * Date: 2019-02-21T22:49Z */ /** Font Family and Sizes */ -#qunit-tests, #qunit-header, #qunit-banner, #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult { +#qunit-tests, #qunit-header, #qunit-banner, #qunit-testrunner-toolbar, #qunit-filteredTest, #qunit-userAgent, #qunit-testresult { font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial, sans-serif; } -#qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult, #qunit-tests li { font-size: small; } +#qunit-testrunner-toolbar, #qunit-filteredTest, #qunit-userAgent, #qunit-testresult, #qunit-tests li { font-size: small; } #qunit-tests { font-size: smaller; } /** Resets */ -#qunit-tests, #qunit-header, #qunit-banner, #qunit-userAgent, #qunit-testresult, #qunit-modulefilter { +#qunit-tests, #qunit-header, #qunit-banner, #qunit-filteredTest, #qunit-userAgent, #qunit-testresult, #qunit-modulefilter { margin: 0; padding: 0; } -/** Header */ +/** Header (excluding toolbar) */ #qunit-header { padding: 0.5em 0 0.5em 1em; @@ -52,45 +52,161 @@ color: #FFF; } -#qunit-testrunner-toolbar label { - display: inline-block; - padding: 0 0.5em 0 0.1em; -} - #qunit-banner { height: 5px; } -#qunit-testrunner-toolbar { +#qunit-filteredTest { padding: 0.5em 1em 0.5em 1em; - color: #5E740B; - background-color: #EEE; - overflow: hidden; + color: #366097; + background-color: #F4FF77; } #qunit-userAgent { padding: 0.5em 1em 0.5em 1em; - background-color: #2B81AF; color: #FFF; + background-color: #2B81AF; text-shadow: rgba(0, 0, 0, 0.5) 2px 2px 1px; } -#qunit-modulefilter-container { - float: right; - padding: 0.2em; + +/** Toolbar */ + +#qunit-testrunner-toolbar { + padding: 0.5em 1em 0.5em 1em; + color: #5E740B; + background-color: #EEE; } -.qunit-url-config { +#qunit-testrunner-toolbar .clearfix { + height: 0; + clear: both; +} + +#qunit-testrunner-toolbar label { display: inline-block; - padding: 0.1em; } -.qunit-filter { - display: block; +#qunit-testrunner-toolbar input[type=checkbox], +#qunit-testrunner-toolbar input[type=radio] { + margin: 3px; + vertical-align: -2px; +} + +#qunit-testrunner-toolbar input[type=text] { + box-sizing: border-box; + height: 1.6em; +} + +.qunit-url-config, +.qunit-filter, +#qunit-modulefilter { + display: inline-block; + line-height: 2.1em; +} + +.qunit-filter, +#qunit-modulefilter { float: right; + position: relative; margin-left: 1em; } +.qunit-url-config label { + margin-right: 0.5em; +} + +#qunit-modulefilter-search { + box-sizing: border-box; + width: 400px; +} + +#qunit-modulefilter-search-container:after { + position: absolute; + right: 0.3em; + content: "\25bc"; + color: black; +} + +#qunit-modulefilter-dropdown { + /* align with #qunit-modulefilter-search */ + box-sizing: border-box; + width: 400px; + position: absolute; + right: 0; + top: 50%; + margin-top: 0.8em; + + border: 1px solid #D3D3D3; + border-top: none; + border-radius: 0 0 .25em .25em; + color: #000; + background-color: #F5F5F5; + z-index: 99; +} + +#qunit-modulefilter-dropdown a { + color: inherit; + text-decoration: none; +} + +#qunit-modulefilter-dropdown .clickable.checked { + font-weight: bold; + color: #000; + background-color: #D2E0E6; +} + +#qunit-modulefilter-dropdown .clickable:hover { + color: #FFF; + background-color: #0D3349; +} + +#qunit-modulefilter-actions { + display: block; + overflow: auto; + + /* align with #qunit-modulefilter-dropdown-list */ + font: smaller/1.5em sans-serif; +} + +#qunit-modulefilter-dropdown #qunit-modulefilter-actions > * { + box-sizing: border-box; + max-height: 2.8em; + display: block; + padding: 0.4em; +} + +#qunit-modulefilter-dropdown #qunit-modulefilter-actions > button { + float: right; + font: inherit; +} + +#qunit-modulefilter-dropdown #qunit-modulefilter-actions > :last-child { + /* insert padding to align with checkbox margins */ + padding-left: 3px; +} + +#qunit-modulefilter-dropdown-list { + max-height: 200px; + overflow-y: auto; + margin: 0; + border-top: 2px groove threedhighlight; + padding: 0.4em 0 0; + font: smaller/1.5em sans-serif; +} + +#qunit-modulefilter-dropdown-list li { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +#qunit-modulefilter-dropdown-list .clickable { + display: block; + padding-left: 0.15em; +} + + /** Tests: Pass/Fail */ #qunit-tests { @@ -110,13 +226,24 @@ #qunit-tests li.running, #qunit-tests li.pass, #qunit-tests li.fail, -#qunit-tests li.skipped { +#qunit-tests li.skipped, +#qunit-tests li.aborted { display: list-item; } +#qunit-tests.hidepass { + position: relative; +} + #qunit-tests.hidepass li.running, -#qunit-tests.hidepass li.pass { - display: none; +#qunit-tests.hidepass li.pass:not(.todo) { + visibility: hidden; + position: absolute; + width: 0; + height: 0; + padding: 0; + border: 0; + margin: 0; } #qunit-tests li strong { @@ -132,6 +259,11 @@ color: #C2CCD1; text-decoration: none; } + +#qunit-tests li p a { + padding: 0.25em; + color: #6B6464; +} #qunit-tests li a:hover, #qunit-tests li a:focus { color: #000; @@ -151,6 +283,10 @@ border-radius: 5px; } +.qunit-source { + margin: 0.6em 0 0.3em; +} + .qunit-collapsed { display: none; } @@ -177,14 +313,14 @@ } #qunit-tests del { - background-color: #E0F2BE; color: #374E0C; + background-color: #E0F2BE; text-decoration: none; } #qunit-tests ins { - background-color: #FFCACA; color: #500; + background-color: #FFCACA; text-decoration: none; } @@ -239,12 +375,16 @@ #qunit-banner.qunit-fail { background-color: #EE5757; } + +/*** Aborted tests */ +#qunit-tests .aborted { color: #000; background-color: orange; } /*** Skipped tests */ #qunit-tests .skipped { background-color: #EBECE9; } +#qunit-tests .qunit-todo-label, #qunit-tests .qunit-skipped-label { background-color: #F4FF77; display: inline-block; @@ -255,19 +395,35 @@ margin: -0.4em 0.4em -0.4em 0; } +#qunit-tests .qunit-todo-label { + background-color: #EEE; +} + /** Result */ #qunit-testresult { - padding: 0.5em 1em 0.5em 1em; - color: #2B81AF; background-color: #D2E0E6; border-bottom: 1px solid #FFF; } +#qunit-testresult .clearfix { + height: 0; + clear: both; +} #qunit-testresult .module-name { font-weight: 700; } +#qunit-testresult-display { + padding: 0.5em 1em 0.5em 1em; + width: 85%; + float:left; +} +#qunit-testresult-controls { + padding: 0.5em 1em 0.5em 1em; + width: 10%; + float:left; +} /** Fixture */ diff --git a/test/lib/qunit-2.9.2.js b/test/lib/qunit-2.9.2.js new file mode 100644 index 00000000..f66e5c72 --- /dev/null +++ b/test/lib/qunit-2.9.2.js @@ -0,0 +1,6604 @@ +/*! + * QUnit 2.9.2 + * https://qunitjs.com/ + * + * Copyright jQuery Foundation and other contributors + * Released under the MIT license + * https://jquery.org/license + * + * Date: 2019-02-21T22:49Z + */ +(function (global$1) { + 'use strict'; + + global$1 = global$1 && global$1.hasOwnProperty('default') ? global$1['default'] : global$1; + + var window$1 = global$1.window; + var self$1 = global$1.self; + var console = global$1.console; + var setTimeout$1 = global$1.setTimeout; + var clearTimeout = global$1.clearTimeout; + + var document$1 = window$1 && window$1.document; + var navigator = window$1 && window$1.navigator; + + var localSessionStorage = function () { + var x = "qunit-test-string"; + try { + global$1.sessionStorage.setItem(x, x); + global$1.sessionStorage.removeItem(x); + return global$1.sessionStorage; + } catch (e) { + return undefined; + } + }(); + + /** + * Returns a function that proxies to the given method name on the globals + * console object. The proxy will also detect if the console doesn't exist and + * will appropriately no-op. This allows support for IE9, which doesn't have a + * console if the developer tools are not open. + */ + function consoleProxy(method) { + return function () { + if (console) { + console[method].apply(console, arguments); + } + }; + } + + var Logger = { + warn: consoleProxy("warn") + }; + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + + + + + + + + + + + + var classCallCheck = function (instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + }; + + var createClass = function () { + function defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + + return function (Constructor, protoProps, staticProps) { + if (protoProps) defineProperties(Constructor.prototype, protoProps); + if (staticProps) defineProperties(Constructor, staticProps); + return Constructor; + }; + }(); + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + var toConsumableArray = function (arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; + + return arr2; + } else { + return Array.from(arr); + } + }; + + var toString = Object.prototype.toString; + var hasOwn = Object.prototype.hasOwnProperty; + var now = Date.now || function () { + return new Date().getTime(); + }; + + var hasPerformanceApi = detectPerformanceApi(); + var performance = hasPerformanceApi ? window$1.performance : undefined; + var performanceNow = hasPerformanceApi ? performance.now.bind(performance) : now; + + function detectPerformanceApi() { + return window$1 && typeof window$1.performance !== "undefined" && typeof window$1.performance.mark === "function" && typeof window$1.performance.measure === "function"; + } + + function measure(comment, startMark, endMark) { + + // `performance.measure` may fail if the mark could not be found. + // reasons a specific mark could not be found include: outside code invoking `performance.clearMarks()` + try { + performance.measure(comment, startMark, endMark); + } catch (ex) { + Logger.warn("performance.measure could not be executed because of ", ex.message); + } + } + + var defined = { + document: window$1 && window$1.document !== undefined, + setTimeout: setTimeout$1 !== undefined + }; + + // Returns a new Array with the elements that are in a but not in b + function diff(a, b) { + var i, + j, + result = a.slice(); + + for (i = 0; i < result.length; i++) { + for (j = 0; j < b.length; j++) { + if (result[i] === b[j]) { + result.splice(i, 1); + i--; + break; + } + } + } + return result; + } + + /** + * Determines whether an element exists in a given array or not. + * + * @method inArray + * @param {Any} elem + * @param {Array} array + * @return {Boolean} + */ + function inArray(elem, array) { + return array.indexOf(elem) !== -1; + } + + /** + * Makes a clone of an object using only Array or Object as base, + * and copies over the own enumerable properties. + * + * @param {Object} obj + * @return {Object} New object with only the own properties (recursively). + */ + function objectValues(obj) { + var key, + val, + vals = is("array", obj) ? [] : {}; + for (key in obj) { + if (hasOwn.call(obj, key)) { + val = obj[key]; + vals[key] = val === Object(val) ? objectValues(val) : val; + } + } + return vals; + } + + function extend(a, b, undefOnly) { + for (var prop in b) { + if (hasOwn.call(b, prop)) { + if (b[prop] === undefined) { + delete a[prop]; + } else if (!(undefOnly && typeof a[prop] !== "undefined")) { + a[prop] = b[prop]; + } + } + } + + return a; + } + + function objectType(obj) { + if (typeof obj === "undefined") { + return "undefined"; + } + + // Consider: typeof null === object + if (obj === null) { + return "null"; + } + + var match = toString.call(obj).match(/^\[object\s(.*)\]$/), + type = match && match[1]; + + switch (type) { + case "Number": + if (isNaN(obj)) { + return "nan"; + } + return "number"; + case "String": + case "Boolean": + case "Array": + case "Set": + case "Map": + case "Date": + case "RegExp": + case "Function": + case "Symbol": + return type.toLowerCase(); + default: + return typeof obj === "undefined" ? "undefined" : _typeof(obj); + } + } + + // Safe object type checking + function is(type, obj) { + return objectType(obj) === type; + } + + // Based on Java's String.hashCode, a simple but not + // rigorously collision resistant hashing function + function generateHash(module, testName) { + var str = module + "\x1C" + testName; + var hash = 0; + + for (var i = 0; i < str.length; i++) { + hash = (hash << 5) - hash + str.charCodeAt(i); + hash |= 0; + } + + // Convert the possibly negative integer hash code into an 8 character hex string, which isn't + // strictly necessary but increases user understanding that the id is a SHA-like hash + var hex = (0x100000000 + hash).toString(16); + if (hex.length < 8) { + hex = "0000000" + hex; + } + + return hex.slice(-8); + } + + // Test for equality any JavaScript type. + // Authors: Philippe Rathé , David Chan + var equiv = (function () { + + // Value pairs queued for comparison. Used for breadth-first processing order, recursion + // detection and avoiding repeated comparison (see below for details). + // Elements are { a: val, b: val }. + var pairs = []; + + var getProto = Object.getPrototypeOf || function (obj) { + return obj.__proto__; + }; + + function useStrictEquality(a, b) { + + // This only gets called if a and b are not strict equal, and is used to compare on + // the primitive values inside object wrappers. For example: + // `var i = 1;` + // `var j = new Number(1);` + // Neither a nor b can be null, as a !== b and they have the same type. + if ((typeof a === "undefined" ? "undefined" : _typeof(a)) === "object") { + a = a.valueOf(); + } + if ((typeof b === "undefined" ? "undefined" : _typeof(b)) === "object") { + b = b.valueOf(); + } + + return a === b; + } + + function compareConstructors(a, b) { + var protoA = getProto(a); + var protoB = getProto(b); + + // Comparing constructors is more strict than using `instanceof` + if (a.constructor === b.constructor) { + return true; + } + + // Ref #851 + // If the obj prototype descends from a null constructor, treat it + // as a null prototype. + if (protoA && protoA.constructor === null) { + protoA = null; + } + if (protoB && protoB.constructor === null) { + protoB = null; + } + + // Allow objects with no prototype to be equivalent to + // objects with Object as their constructor. + if (protoA === null && protoB === Object.prototype || protoB === null && protoA === Object.prototype) { + return true; + } + + return false; + } + + function getRegExpFlags(regexp) { + return "flags" in regexp ? regexp.flags : regexp.toString().match(/[gimuy]*$/)[0]; + } + + function isContainer(val) { + return ["object", "array", "map", "set"].indexOf(objectType(val)) !== -1; + } + + function breadthFirstCompareChild(a, b) { + + // If a is a container not reference-equal to b, postpone the comparison to the + // end of the pairs queue -- unless (a, b) has been seen before, in which case skip + // over the pair. + if (a === b) { + return true; + } + if (!isContainer(a)) { + return typeEquiv(a, b); + } + if (pairs.every(function (pair) { + return pair.a !== a || pair.b !== b; + })) { + + // Not yet started comparing this pair + pairs.push({ a: a, b: b }); + } + return true; + } + + var callbacks = { + "string": useStrictEquality, + "boolean": useStrictEquality, + "number": useStrictEquality, + "null": useStrictEquality, + "undefined": useStrictEquality, + "symbol": useStrictEquality, + "date": useStrictEquality, + + "nan": function nan() { + return true; + }, + + "regexp": function regexp(a, b) { + return a.source === b.source && + + // Include flags in the comparison + getRegExpFlags(a) === getRegExpFlags(b); + }, + + // abort (identical references / instance methods were skipped earlier) + "function": function _function() { + return false; + }, + + "array": function array(a, b) { + var i, len; + + len = a.length; + if (len !== b.length) { + + // Safe and faster + return false; + } + + for (i = 0; i < len; i++) { + + // Compare non-containers; queue non-reference-equal containers + if (!breadthFirstCompareChild(a[i], b[i])) { + return false; + } + } + return true; + }, + + // Define sets a and b to be equivalent if for each element aVal in a, there + // is some element bVal in b such that aVal and bVal are equivalent. Element + // repetitions are not counted, so these are equivalent: + // a = new Set( [ {}, [], [] ] ); + // b = new Set( [ {}, {}, [] ] ); + "set": function set$$1(a, b) { + var innerEq, + outerEq = true; + + if (a.size !== b.size) { + + // This optimization has certain quirks because of the lack of + // repetition counting. For instance, adding the same + // (reference-identical) element to two equivalent sets can + // make them non-equivalent. + return false; + } + + a.forEach(function (aVal) { + + // Short-circuit if the result is already known. (Using for...of + // with a break clause would be cleaner here, but it would cause + // a syntax error on older Javascript implementations even if + // Set is unused) + if (!outerEq) { + return; + } + + innerEq = false; + + b.forEach(function (bVal) { + var parentPairs; + + // Likewise, short-circuit if the result is already known + if (innerEq) { + return; + } + + // Swap out the global pairs list, as the nested call to + // innerEquiv will clobber its contents + parentPairs = pairs; + if (innerEquiv(bVal, aVal)) { + innerEq = true; + } + + // Replace the global pairs list + pairs = parentPairs; + }); + + if (!innerEq) { + outerEq = false; + } + }); + + return outerEq; + }, + + // Define maps a and b to be equivalent if for each key-value pair (aKey, aVal) + // in a, there is some key-value pair (bKey, bVal) in b such that + // [ aKey, aVal ] and [ bKey, bVal ] are equivalent. Key repetitions are not + // counted, so these are equivalent: + // a = new Map( [ [ {}, 1 ], [ {}, 1 ], [ [], 1 ] ] ); + // b = new Map( [ [ {}, 1 ], [ [], 1 ], [ [], 1 ] ] ); + "map": function map(a, b) { + var innerEq, + outerEq = true; + + if (a.size !== b.size) { + + // This optimization has certain quirks because of the lack of + // repetition counting. For instance, adding the same + // (reference-identical) key-value pair to two equivalent maps + // can make them non-equivalent. + return false; + } + + a.forEach(function (aVal, aKey) { + + // Short-circuit if the result is already known. (Using for...of + // with a break clause would be cleaner here, but it would cause + // a syntax error on older Javascript implementations even if + // Map is unused) + if (!outerEq) { + return; + } + + innerEq = false; + + b.forEach(function (bVal, bKey) { + var parentPairs; + + // Likewise, short-circuit if the result is already known + if (innerEq) { + return; + } + + // Swap out the global pairs list, as the nested call to + // innerEquiv will clobber its contents + parentPairs = pairs; + if (innerEquiv([bVal, bKey], [aVal, aKey])) { + innerEq = true; + } + + // Replace the global pairs list + pairs = parentPairs; + }); + + if (!innerEq) { + outerEq = false; + } + }); + + return outerEq; + }, + + "object": function object(a, b) { + var i, + aProperties = [], + bProperties = []; + + if (compareConstructors(a, b) === false) { + return false; + } + + // Be strict: don't ensure hasOwnProperty and go deep + for (i in a) { + + // Collect a's properties + aProperties.push(i); + + // Skip OOP methods that look the same + if (a.constructor !== Object && typeof a.constructor !== "undefined" && typeof a[i] === "function" && typeof b[i] === "function" && a[i].toString() === b[i].toString()) { + continue; + } + + // Compare non-containers; queue non-reference-equal containers + if (!breadthFirstCompareChild(a[i], b[i])) { + return false; + } + } + + for (i in b) { + + // Collect b's properties + bProperties.push(i); + } + + // Ensures identical properties name + return typeEquiv(aProperties.sort(), bProperties.sort()); + } + }; + + function typeEquiv(a, b) { + var type = objectType(a); + + // Callbacks for containers will append to the pairs queue to achieve breadth-first + // search order. The pairs queue is also used to avoid reprocessing any pair of + // containers that are reference-equal to a previously visited pair (a special case + // this being recursion detection). + // + // Because of this approach, once typeEquiv returns a false value, it should not be + // called again without clearing the pair queue else it may wrongly report a visited + // pair as being equivalent. + return objectType(b) === type && callbacks[type](a, b); + } + + function innerEquiv(a, b) { + var i, pair; + + // We're done when there's nothing more to compare + if (arguments.length < 2) { + return true; + } + + // Clear the global pair queue and add the top-level values being compared + pairs = [{ a: a, b: b }]; + + for (i = 0; i < pairs.length; i++) { + pair = pairs[i]; + + // Perform type-specific comparison on any pairs that are not strictly + // equal. For container types, that comparison will postpone comparison + // of any sub-container pair to the end of the pair queue. This gives + // breadth-first search order. It also avoids the reprocessing of + // reference-equal siblings, cousins etc, which can have a significant speed + // impact when comparing a container of small objects each of which has a + // reference to the same (singleton) large object. + if (pair.a !== pair.b && !typeEquiv(pair.a, pair.b)) { + return false; + } + } + + // ...across all consecutive argument pairs + return arguments.length === 2 || innerEquiv.apply(this, [].slice.call(arguments, 1)); + } + + return function () { + var result = innerEquiv.apply(undefined, arguments); + + // Release any retained objects + pairs.length = 0; + return result; + }; + })(); + + /** + * Config object: Maintain internal state + * Later exposed as QUnit.config + * `config` initialized at top of scope + */ + var config = { + + // The queue of tests to run + queue: [], + + // Block until document ready + blocking: true, + + // By default, run previously failed tests first + // very useful in combination with "Hide passed tests" checked + reorder: true, + + // By default, modify document.title when suite is done + altertitle: true, + + // HTML Reporter: collapse every test except the first failing test + // If false, all failing tests will be expanded + collapse: true, + + // By default, scroll to top of the page when suite is done + scrolltop: true, + + // Depth up-to which object will be dumped + maxDepth: 5, + + // When enabled, all tests must call expect() + requireExpects: false, + + // Placeholder for user-configurable form-exposed URL parameters + urlConfig: [], + + // Set of all modules. + modules: [], + + // The first unnamed module + currentModule: { + name: "", + tests: [], + childModules: [], + testsRun: 0, + unskippedTestsRun: 0, + hooks: { + before: [], + beforeEach: [], + afterEach: [], + after: [] + } + }, + + callbacks: {}, + + // The storage module to use for reordering tests + storage: localSessionStorage + }; + + // take a predefined QUnit.config and extend the defaults + var globalConfig = window$1 && window$1.QUnit && window$1.QUnit.config; + + // only extend the global config if there is no QUnit overload + if (window$1 && window$1.QUnit && !window$1.QUnit.version) { + extend(config, globalConfig); + } + + // Push a loose unnamed module to the modules collection + config.modules.push(config.currentModule); + + // Based on jsDump by Ariel Flesler + // http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html + var dump = (function () { + function quote(str) { + return "\"" + str.toString().replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\""; + } + function literal(o) { + return o + ""; + } + function join(pre, arr, post) { + var s = dump.separator(), + base = dump.indent(), + inner = dump.indent(1); + if (arr.join) { + arr = arr.join("," + s + inner); + } + if (!arr) { + return pre + post; + } + return [pre, inner + arr, base + post].join(s); + } + function array(arr, stack) { + var i = arr.length, + ret = new Array(i); + + if (dump.maxDepth && dump.depth > dump.maxDepth) { + return "[object Array]"; + } + + this.up(); + while (i--) { + ret[i] = this.parse(arr[i], undefined, stack); + } + this.down(); + return join("[", ret, "]"); + } + + function isArray(obj) { + return ( + + //Native Arrays + toString.call(obj) === "[object Array]" || + + // NodeList objects + typeof obj.length === "number" && obj.item !== undefined && (obj.length ? obj.item(0) === obj[0] : obj.item(0) === null && obj[0] === undefined) + ); + } + + var reName = /^function (\w+)/, + dump = { + + // The objType is used mostly internally, you can fix a (custom) type in advance + parse: function parse(obj, objType, stack) { + stack = stack || []; + var res, + parser, + parserType, + objIndex = stack.indexOf(obj); + + if (objIndex !== -1) { + return "recursion(" + (objIndex - stack.length) + ")"; + } + + objType = objType || this.typeOf(obj); + parser = this.parsers[objType]; + parserType = typeof parser === "undefined" ? "undefined" : _typeof(parser); + + if (parserType === "function") { + stack.push(obj); + res = parser.call(this, obj, stack); + stack.pop(); + return res; + } + return parserType === "string" ? parser : this.parsers.error; + }, + typeOf: function typeOf(obj) { + var type; + + if (obj === null) { + type = "null"; + } else if (typeof obj === "undefined") { + type = "undefined"; + } else if (is("regexp", obj)) { + type = "regexp"; + } else if (is("date", obj)) { + type = "date"; + } else if (is("function", obj)) { + type = "function"; + } else if (obj.setInterval !== undefined && obj.document !== undefined && obj.nodeType === undefined) { + type = "window"; + } else if (obj.nodeType === 9) { + type = "document"; + } else if (obj.nodeType) { + type = "node"; + } else if (isArray(obj)) { + type = "array"; + } else if (obj.constructor === Error.prototype.constructor) { + type = "error"; + } else { + type = typeof obj === "undefined" ? "undefined" : _typeof(obj); + } + return type; + }, + + separator: function separator() { + if (this.multiline) { + return this.HTML ? "
                " : "\n"; + } else { + return this.HTML ? " " : " "; + } + }, + + // Extra can be a number, shortcut for increasing-calling-decreasing + indent: function indent(extra) { + if (!this.multiline) { + return ""; + } + var chr = this.indentChar; + if (this.HTML) { + chr = chr.replace(/\t/g, " ").replace(/ /g, " "); + } + return new Array(this.depth + (extra || 0)).join(chr); + }, + up: function up(a) { + this.depth += a || 1; + }, + down: function down(a) { + this.depth -= a || 1; + }, + setParser: function setParser(name, parser) { + this.parsers[name] = parser; + }, + + // The next 3 are exposed so you can use them + quote: quote, + literal: literal, + join: join, + depth: 1, + maxDepth: config.maxDepth, + + // This is the list of parsers, to modify them, use dump.setParser + parsers: { + window: "[Window]", + document: "[Document]", + error: function error(_error) { + return "Error(\"" + _error.message + "\")"; + }, + unknown: "[Unknown]", + "null": "null", + "undefined": "undefined", + "function": function _function(fn) { + var ret = "function", + + + // Functions never have name in IE + name = "name" in fn ? fn.name : (reName.exec(fn) || [])[1]; + + if (name) { + ret += " " + name; + } + ret += "("; + + ret = [ret, dump.parse(fn, "functionArgs"), "){"].join(""); + return join(ret, dump.parse(fn, "functionCode"), "}"); + }, + array: array, + nodelist: array, + "arguments": array, + object: function object(map, stack) { + var keys, + key, + val, + i, + nonEnumerableProperties, + ret = []; + + if (dump.maxDepth && dump.depth > dump.maxDepth) { + return "[object Object]"; + } + + dump.up(); + keys = []; + for (key in map) { + keys.push(key); + } + + // Some properties are not always enumerable on Error objects. + nonEnumerableProperties = ["message", "name"]; + for (i in nonEnumerableProperties) { + key = nonEnumerableProperties[i]; + if (key in map && !inArray(key, keys)) { + keys.push(key); + } + } + keys.sort(); + for (i = 0; i < keys.length; i++) { + key = keys[i]; + val = map[key]; + ret.push(dump.parse(key, "key") + ": " + dump.parse(val, undefined, stack)); + } + dump.down(); + return join("{", ret, "}"); + }, + node: function node(_node) { + var len, + i, + val, + open = dump.HTML ? "<" : "<", + close = dump.HTML ? ">" : ">", + tag = _node.nodeName.toLowerCase(), + ret = open + tag, + attrs = _node.attributes; + + if (attrs) { + for (i = 0, len = attrs.length; i < len; i++) { + val = attrs[i].nodeValue; + + // IE6 includes all attributes in .attributes, even ones not explicitly + // set. Those have values like undefined, null, 0, false, "" or + // "inherit". + if (val && val !== "inherit") { + ret += " " + attrs[i].nodeName + "=" + dump.parse(val, "attribute"); + } + } + } + ret += close; + + // Show content of TextNode or CDATASection + if (_node.nodeType === 3 || _node.nodeType === 4) { + ret += _node.nodeValue; + } + + return ret + open + "/" + tag + close; + }, + + // Function calls it internally, it's the arguments part of the function + functionArgs: function functionArgs(fn) { + var args, + l = fn.length; + + if (!l) { + return ""; + } + + args = new Array(l); + while (l--) { + + // 97 is 'a' + args[l] = String.fromCharCode(97 + l); + } + return " " + args.join(", ") + " "; + }, + + // Object calls it internally, the key part of an item in a map + key: quote, + + // Function calls it internally, it's the content of the function + functionCode: "[code]", + + // Node calls it internally, it's a html attribute value + attribute: quote, + string: quote, + date: quote, + regexp: literal, + number: literal, + "boolean": literal, + symbol: function symbol(sym) { + return sym.toString(); + } + }, + + // If true, entities are escaped ( <, >, \t, space and \n ) + HTML: false, + + // Indentation unit + indentChar: " ", + + // If true, items in a collection, are separated by a \n, else just a space. + multiline: true + }; + + return dump; + })(); + + var SuiteReport = function () { + function SuiteReport(name, parentSuite) { + classCallCheck(this, SuiteReport); + + this.name = name; + this.fullName = parentSuite ? parentSuite.fullName.concat(name) : []; + + this.tests = []; + this.childSuites = []; + + if (parentSuite) { + parentSuite.pushChildSuite(this); + } + } + + createClass(SuiteReport, [{ + key: "start", + value: function start(recordTime) { + if (recordTime) { + this._startTime = performanceNow(); + + if (performance) { + var suiteLevel = this.fullName.length; + performance.mark("qunit_suite_" + suiteLevel + "_start"); + } + } + + return { + name: this.name, + fullName: this.fullName.slice(), + tests: this.tests.map(function (test) { + return test.start(); + }), + childSuites: this.childSuites.map(function (suite) { + return suite.start(); + }), + testCounts: { + total: this.getTestCounts().total + } + }; + } + }, { + key: "end", + value: function end(recordTime) { + if (recordTime) { + this._endTime = performanceNow(); + + if (performance) { + var suiteLevel = this.fullName.length; + performance.mark("qunit_suite_" + suiteLevel + "_end"); + + var suiteName = this.fullName.join(" – "); + + measure(suiteLevel === 0 ? "QUnit Test Run" : "QUnit Test Suite: " + suiteName, "qunit_suite_" + suiteLevel + "_start", "qunit_suite_" + suiteLevel + "_end"); + } + } + + return { + name: this.name, + fullName: this.fullName.slice(), + tests: this.tests.map(function (test) { + return test.end(); + }), + childSuites: this.childSuites.map(function (suite) { + return suite.end(); + }), + testCounts: this.getTestCounts(), + runtime: this.getRuntime(), + status: this.getStatus() + }; + } + }, { + key: "pushChildSuite", + value: function pushChildSuite(suite) { + this.childSuites.push(suite); + } + }, { + key: "pushTest", + value: function pushTest(test) { + this.tests.push(test); + } + }, { + key: "getRuntime", + value: function getRuntime() { + return this._endTime - this._startTime; + } + }, { + key: "getTestCounts", + value: function getTestCounts() { + var counts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { passed: 0, failed: 0, skipped: 0, todo: 0, total: 0 }; + + counts = this.tests.reduce(function (counts, test) { + if (test.valid) { + counts[test.getStatus()]++; + counts.total++; + } + + return counts; + }, counts); + + return this.childSuites.reduce(function (counts, suite) { + return suite.getTestCounts(counts); + }, counts); + } + }, { + key: "getStatus", + value: function getStatus() { + var _getTestCounts = this.getTestCounts(), + total = _getTestCounts.total, + failed = _getTestCounts.failed, + skipped = _getTestCounts.skipped, + todo = _getTestCounts.todo; + + if (failed) { + return "failed"; + } else { + if (skipped === total) { + return "skipped"; + } else if (todo === total) { + return "todo"; + } else { + return "passed"; + } + } + } + }]); + return SuiteReport; + }(); + + var focused = false; + + var moduleStack = []; + + function createModule(name, testEnvironment, modifiers) { + var parentModule = moduleStack.length ? moduleStack.slice(-1)[0] : null; + var moduleName = parentModule !== null ? [parentModule.name, name].join(" > ") : name; + var parentSuite = parentModule ? parentModule.suiteReport : globalSuite; + + var skip = parentModule !== null && parentModule.skip || modifiers.skip; + var todo = parentModule !== null && parentModule.todo || modifiers.todo; + + var module = { + name: moduleName, + parentModule: parentModule, + tests: [], + moduleId: generateHash(moduleName), + testsRun: 0, + unskippedTestsRun: 0, + childModules: [], + suiteReport: new SuiteReport(name, parentSuite), + + // Pass along `skip` and `todo` properties from parent module, in case + // there is one, to childs. And use own otherwise. + // This property will be used to mark own tests and tests of child suites + // as either `skipped` or `todo`. + skip: skip, + todo: skip ? false : todo + }; + + var env = {}; + if (parentModule) { + parentModule.childModules.push(module); + extend(env, parentModule.testEnvironment); + } + extend(env, testEnvironment); + module.testEnvironment = env; + + config.modules.push(module); + return module; + } + + function processModule(name, options, executeNow) { + var modifiers = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + + if (objectType(options) === "function") { + executeNow = options; + options = undefined; + } + + var module = createModule(name, options, modifiers); + + // Move any hooks to a 'hooks' object + var testEnvironment = module.testEnvironment; + var hooks = module.hooks = {}; + + setHookFromEnvironment(hooks, testEnvironment, "before"); + setHookFromEnvironment(hooks, testEnvironment, "beforeEach"); + setHookFromEnvironment(hooks, testEnvironment, "afterEach"); + setHookFromEnvironment(hooks, testEnvironment, "after"); + + var moduleFns = { + before: setHookFunction(module, "before"), + beforeEach: setHookFunction(module, "beforeEach"), + afterEach: setHookFunction(module, "afterEach"), + after: setHookFunction(module, "after") + }; + + var currentModule = config.currentModule; + if (objectType(executeNow) === "function") { + moduleStack.push(module); + config.currentModule = module; + executeNow.call(module.testEnvironment, moduleFns); + moduleStack.pop(); + module = module.parentModule || currentModule; + } + + config.currentModule = module; + + function setHookFromEnvironment(hooks, environment, name) { + var potentialHook = environment[name]; + hooks[name] = typeof potentialHook === "function" ? [potentialHook] : []; + delete environment[name]; + } + + function setHookFunction(module, hookName) { + return function setHook(callback) { + module.hooks[hookName].push(callback); + }; + } + } + + function module$1(name, options, executeNow) { + if (focused) { + return; + } + + processModule(name, options, executeNow); + } + + module$1.only = function () { + if (focused) { + return; + } + + config.modules.length = 0; + config.queue.length = 0; + + module$1.apply(undefined, arguments); + + focused = true; + }; + + module$1.skip = function (name, options, executeNow) { + if (focused) { + return; + } + + processModule(name, options, executeNow, { skip: true }); + }; + + module$1.todo = function (name, options, executeNow) { + if (focused) { + return; + } + + processModule(name, options, executeNow, { todo: true }); + }; + + var LISTENERS = Object.create(null); + var SUPPORTED_EVENTS = ["runStart", "suiteStart", "testStart", "assertion", "testEnd", "suiteEnd", "runEnd"]; + + /** + * Emits an event with the specified data to all currently registered listeners. + * Callbacks will fire in the order in which they are registered (FIFO). This + * function is not exposed publicly; it is used by QUnit internals to emit + * logging events. + * + * @private + * @method emit + * @param {String} eventName + * @param {Object} data + * @return {Void} + */ + function emit(eventName, data) { + if (objectType(eventName) !== "string") { + throw new TypeError("eventName must be a string when emitting an event"); + } + + // Clone the callbacks in case one of them registers a new callback + var originalCallbacks = LISTENERS[eventName]; + var callbacks = originalCallbacks ? [].concat(toConsumableArray(originalCallbacks)) : []; + + for (var i = 0; i < callbacks.length; i++) { + callbacks[i](data); + } + } + + /** + * Registers a callback as a listener to the specified event. + * + * @public + * @method on + * @param {String} eventName + * @param {Function} callback + * @return {Void} + */ + function on(eventName, callback) { + if (objectType(eventName) !== "string") { + throw new TypeError("eventName must be a string when registering a listener"); + } else if (!inArray(eventName, SUPPORTED_EVENTS)) { + var events = SUPPORTED_EVENTS.join(", "); + throw new Error("\"" + eventName + "\" is not a valid event; must be one of: " + events + "."); + } else if (objectType(callback) !== "function") { + throw new TypeError("callback must be a function when registering a listener"); + } + + if (!LISTENERS[eventName]) { + LISTENERS[eventName] = []; + } + + // Don't register the same callback more than once + if (!inArray(callback, LISTENERS[eventName])) { + LISTENERS[eventName].push(callback); + } + } + + function objectOrFunction(x) { + var type = typeof x === 'undefined' ? 'undefined' : _typeof(x); + return x !== null && (type === 'object' || type === 'function'); + } + + function isFunction(x) { + return typeof x === 'function'; + } + + + + var _isArray = void 0; + if (Array.isArray) { + _isArray = Array.isArray; + } else { + _isArray = function _isArray(x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; + } + + var isArray = _isArray; + + var len = 0; + var vertxNext = void 0; + var customSchedulerFn = void 0; + + var asap = function asap(callback, arg) { + queue[len] = callback; + queue[len + 1] = arg; + len += 2; + if (len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + if (customSchedulerFn) { + customSchedulerFn(flush); + } else { + scheduleFlush(); + } + } + }; + + function setScheduler(scheduleFn) { + customSchedulerFn = scheduleFn; + } + + function setAsap(asapFn) { + asap = asapFn; + } + + var browserWindow = typeof window !== 'undefined' ? window : undefined; + var browserGlobal = browserWindow || {}; + var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; + var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; + + // test for web worker but not in IE10 + var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; + + // node + function useNextTick() { + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // see https://github.com/cujojs/when/issues/410 for details + return function () { + return process.nextTick(flush); + }; + } + + // vertx + function useVertxTimer() { + if (typeof vertxNext !== 'undefined') { + return function () { + vertxNext(flush); + }; + } + + return useSetTimeout(); + } + + function useMutationObserver() { + var iterations = 0; + var observer = new BrowserMutationObserver(flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function () { + node.data = iterations = ++iterations % 2; + }; + } + + // web worker + function useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = flush; + return function () { + return channel.port2.postMessage(0); + }; + } + + function useSetTimeout() { + // Store setTimeout reference so es6-promise will be unaffected by + // other code modifying setTimeout (like sinon.useFakeTimers()) + var globalSetTimeout = setTimeout; + return function () { + return globalSetTimeout(flush, 1); + }; + } + + var queue = new Array(1000); + function flush() { + for (var i = 0; i < len; i += 2) { + var callback = queue[i]; + var arg = queue[i + 1]; + + callback(arg); + + queue[i] = undefined; + queue[i + 1] = undefined; + } + + len = 0; + } + + function attemptVertx() { + try { + var vertx = Function('return this')().require('vertx'); + vertxNext = vertx.runOnLoop || vertx.runOnContext; + return useVertxTimer(); + } catch (e) { + return useSetTimeout(); + } + } + + var scheduleFlush = void 0; + // Decide what async method to use to triggering processing of queued callbacks: + if (isNode) { + scheduleFlush = useNextTick(); + } else if (BrowserMutationObserver) { + scheduleFlush = useMutationObserver(); + } else if (isWorker) { + scheduleFlush = useMessageChannel(); + } else if (browserWindow === undefined && typeof require === 'function') { + scheduleFlush = attemptVertx(); + } else { + scheduleFlush = useSetTimeout(); + } + + function then(onFulfillment, onRejection) { + var parent = this; + + var child = new this.constructor(noop); + + if (child[PROMISE_ID] === undefined) { + makePromise(child); + } + + var _state = parent._state; + + + if (_state) { + var callback = arguments[_state - 1]; + asap(function () { + return invokeCallback(_state, child, callback, parent._result); + }); + } else { + subscribe(parent, child, onFulfillment, onRejection); + } + + return child; + } + + /** + `Promise.resolve` returns a promise that will become resolved with the + passed `value`. It is shorthand for the following: + + ```javascript + let promise = new Promise(function(resolve, reject){ + resolve(1); + }); + + promise.then(function(value){ + // value === 1 + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + let promise = Promise.resolve(1); + + promise.then(function(value){ + // value === 1 + }); + ``` + + @method resolve + @static + @param {Any} value value that the returned promise will be resolved with + Useful for tooling. + @return {Promise} a promise that will become fulfilled with the given + `value` + */ + function resolve$1(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && (typeof object === 'undefined' ? 'undefined' : _typeof(object)) === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor(noop); + resolve(promise, object); + return promise; + } + + var PROMISE_ID = Math.random().toString(36).substring(2); + + function noop() {} + + var PENDING = void 0; + var FULFILLED = 1; + var REJECTED = 2; + + var TRY_CATCH_ERROR = { error: null }; + + function selfFulfillment() { + return new TypeError("You cannot resolve a promise with itself"); + } + + function cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); + } + + function getThen(promise) { + try { + return promise.then; + } catch (error) { + TRY_CATCH_ERROR.error = error; + return TRY_CATCH_ERROR; + } + } + + function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) { + try { + then$$1.call(value, fulfillmentHandler, rejectionHandler); + } catch (e) { + return e; + } + } + + function handleForeignThenable(promise, thenable, then$$1) { + asap(function (promise) { + var sealed = false; + var error = tryThen(then$$1, thenable, function (value) { + if (sealed) { + return; + } + sealed = true; + if (thenable !== value) { + resolve(promise, value); + } else { + fulfill(promise, value); + } + }, function (reason) { + if (sealed) { + return; + } + sealed = true; + + reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + reject(promise, error); + } + }, promise); + } + + function handleOwnThenable(promise, thenable) { + if (thenable._state === FULFILLED) { + fulfill(promise, thenable._result); + } else if (thenable._state === REJECTED) { + reject(promise, thenable._result); + } else { + subscribe(thenable, undefined, function (value) { + return resolve(promise, value); + }, function (reason) { + return reject(promise, reason); + }); + } + } + + function handleMaybeThenable(promise, maybeThenable, then$$1) { + if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) { + handleOwnThenable(promise, maybeThenable); + } else { + if (then$$1 === TRY_CATCH_ERROR) { + reject(promise, TRY_CATCH_ERROR.error); + TRY_CATCH_ERROR.error = null; + } else if (then$$1 === undefined) { + fulfill(promise, maybeThenable); + } else if (isFunction(then$$1)) { + handleForeignThenable(promise, maybeThenable, then$$1); + } else { + fulfill(promise, maybeThenable); + } + } + } + + function resolve(promise, value) { + if (promise === value) { + reject(promise, selfFulfillment()); + } else if (objectOrFunction(value)) { + handleMaybeThenable(promise, value, getThen(value)); + } else { + fulfill(promise, value); + } + } + + function publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + + publish(promise); + } + + function fulfill(promise, value) { + if (promise._state !== PENDING) { + return; + } + + promise._result = value; + promise._state = FULFILLED; + + if (promise._subscribers.length !== 0) { + asap(publish, promise); + } + } + + function reject(promise, reason) { + if (promise._state !== PENDING) { + return; + } + promise._state = REJECTED; + promise._result = reason; + + asap(publishRejection, promise); + } + + function subscribe(parent, child, onFulfillment, onRejection) { + var _subscribers = parent._subscribers; + var length = _subscribers.length; + + + parent._onerror = null; + + _subscribers[length] = child; + _subscribers[length + FULFILLED] = onFulfillment; + _subscribers[length + REJECTED] = onRejection; + + if (length === 0 && parent._state) { + asap(publish, parent); + } + } + + function publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if (subscribers.length === 0) { + return; + } + + var child = void 0, + callback = void 0, + detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } + + promise._subscribers.length = 0; + } + + function tryCatch(callback, detail) { + try { + return callback(detail); + } catch (e) { + TRY_CATCH_ERROR.error = e; + return TRY_CATCH_ERROR; + } + } + + function invokeCallback(settled, promise, callback, detail) { + var hasCallback = isFunction(callback), + value = void 0, + error = void 0, + succeeded = void 0, + failed = void 0; + + if (hasCallback) { + value = tryCatch(callback, detail); + + if (value === TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value.error = null; + } else { + succeeded = true; + } + + if (promise === value) { + reject(promise, cannotReturnOwn()); + return; + } + } else { + value = detail; + succeeded = true; + } + + if (promise._state !== PENDING) { + // noop + } else if (hasCallback && succeeded) { + resolve(promise, value); + } else if (failed) { + reject(promise, error); + } else if (settled === FULFILLED) { + fulfill(promise, value); + } else if (settled === REJECTED) { + reject(promise, value); + } + } + + function initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value) { + resolve(promise, value); + }, function rejectPromise(reason) { + reject(promise, reason); + }); + } catch (e) { + reject(promise, e); + } + } + + var id = 0; + function nextId() { + return id++; + } + + function makePromise(promise) { + promise[PROMISE_ID] = id++; + promise._state = undefined; + promise._result = undefined; + promise._subscribers = []; + } + + function validationError() { + return new Error('Array Methods must be provided an Array'); + } + + var Enumerator = function () { + function Enumerator(Constructor, input) { + classCallCheck(this, Enumerator); + + this._instanceConstructor = Constructor; + this.promise = new Constructor(noop); + + if (!this.promise[PROMISE_ID]) { + makePromise(this.promise); + } + + if (isArray(input)) { + this.length = input.length; + this._remaining = input.length; + + this._result = new Array(this.length); + + if (this.length === 0) { + fulfill(this.promise, this._result); + } else { + this.length = this.length || 0; + this._enumerate(input); + if (this._remaining === 0) { + fulfill(this.promise, this._result); + } + } + } else { + reject(this.promise, validationError()); + } + } + + createClass(Enumerator, [{ + key: '_enumerate', + value: function _enumerate(input) { + for (var i = 0; this._state === PENDING && i < input.length; i++) { + this._eachEntry(input[i], i); + } + } + }, { + key: '_eachEntry', + value: function _eachEntry(entry, i) { + var c = this._instanceConstructor; + var resolve$$1 = c.resolve; + + + if (resolve$$1 === resolve$1) { + var _then = getThen(entry); + + if (_then === then && entry._state !== PENDING) { + this._settledAt(entry._state, i, entry._result); + } else if (typeof _then !== 'function') { + this._remaining--; + this._result[i] = entry; + } else if (c === Promise$2) { + var promise = new c(noop); + handleMaybeThenable(promise, entry, _then); + this._willSettleAt(promise, i); + } else { + this._willSettleAt(new c(function (resolve$$1) { + return resolve$$1(entry); + }), i); + } + } else { + this._willSettleAt(resolve$$1(entry), i); + } + } + }, { + key: '_settledAt', + value: function _settledAt(state, i, value) { + var promise = this.promise; + + + if (promise._state === PENDING) { + this._remaining--; + + if (state === REJECTED) { + reject(promise, value); + } else { + this._result[i] = value; + } + } + + if (this._remaining === 0) { + fulfill(promise, this._result); + } + } + }, { + key: '_willSettleAt', + value: function _willSettleAt(promise, i) { + var enumerator = this; + + subscribe(promise, undefined, function (value) { + return enumerator._settledAt(FULFILLED, i, value); + }, function (reason) { + return enumerator._settledAt(REJECTED, i, reason); + }); + } + }]); + return Enumerator; + }(); + + /** + `Promise.all` accepts an array of promises, and returns a new promise which + is fulfilled with an array of fulfillment values for the passed promises, or + rejected with the reason of the first passed promise to be rejected. It casts all + elements of the passed iterable to promises as it runs this algorithm. + + Example: + + ```javascript + let promise1 = resolve(1); + let promise2 = resolve(2); + let promise3 = resolve(3); + let promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // The array here would be [ 1, 2, 3 ]; + }); + ``` + + If any of the `promises` given to `all` are rejected, the first promise + that is rejected will be given as an argument to the returned promises's + rejection handler. For example: + + Example: + + ```javascript + let promise1 = resolve(1); + let promise2 = reject(new Error("2")); + let promise3 = reject(new Error("3")); + let promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(error) { + // error.message === "2" + }); + ``` + + @method all + @static + @param {Array} entries array of promises + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled when all `promises` have been + fulfilled, or rejected if any of them become rejected. + @static + */ + function all(entries) { + return new Enumerator(this, entries).promise; + } + + /** + `Promise.race` returns a new promise which is settled in the same way as the + first passed promise to settle. + + Example: + + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + let promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 2'); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // result === 'promise 2' because it was resolved before promise1 + // was resolved. + }); + ``` + + `Promise.race` is deterministic in that only the state of the first + settled promise matters. For example, even if other promises given to the + `promises` array argument are resolved, but the first settled promise has + become rejected before the other promises became fulfilled, the returned + promise will become rejected: + + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + let promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + reject(new Error('promise 2')); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // Code here never runs + }, function(reason){ + // reason.message === 'promise 2' because promise 2 became rejected before + // promise 1 became fulfilled + }); + ``` + + An example real-world use case is implementing timeouts: + + ```javascript + Promise.race([ajax('foo.json'), timeout(5000)]) + ``` + + @method race + @static + @param {Array} promises array of promises to observe + Useful for tooling. + @return {Promise} a promise which settles in the same way as the first passed + promise to settle. + */ + function race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + if (!isArray(entries)) { + return new Constructor(function (_, reject) { + return reject(new TypeError('You must pass an array to race.')); + }); + } else { + return new Constructor(function (resolve, reject) { + var length = entries.length; + for (var i = 0; i < length; i++) { + Constructor.resolve(entries[i]).then(resolve, reject); + } + }); + } + } + + /** + `Promise.reject` returns a promise rejected with the passed `reason`. + It is shorthand for the following: + + ```javascript + let promise = new Promise(function(resolve, reject){ + reject(new Error('WHOOPS')); + }); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + let promise = Promise.reject(new Error('WHOOPS')); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + @method reject + @static + @param {Any} reason value that the returned promise will be rejected with. + Useful for tooling. + @return {Promise} a promise rejected with the given `reason`. + */ + function reject$1(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(noop); + reject(promise, reason); + return promise; + } + + function needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); + } + + function needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); + } + + /** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise's eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + let promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + let xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {Function} resolver + Useful for tooling. + @constructor + */ + + var Promise$2 = function () { + function Promise(resolver) { + classCallCheck(this, Promise); + + this[PROMISE_ID] = nextId(); + this._result = this._state = undefined; + this._subscribers = []; + + if (noop !== resolver) { + typeof resolver !== 'function' && needsResolver(); + this instanceof Promise ? initializePromise(this, resolver) : needsNew(); + } + } + + /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + Chaining + -------- + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + Assimilation + ------------ + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + If the assimliated promise rejects, then the downstream promise will also reject. + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + Simple Example + -------------- + Synchronous Example + ```javascript + let result; + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + Errback Example + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + Promise Example; + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + Advanced Example + -------------- + Synchronous Example + ```javascript + let author, books; + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + Errback Example + ```js + function foundBooks(books) { + } + function failure(reason) { + } + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + Promise Example; + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} + */ + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} + */ + + + createClass(Promise, [{ + key: 'catch', + value: function _catch(onRejection) { + return this.then(null, onRejection); + } + + /** + `finally` will be invoked regardless of the promise's fate just as native + try/catch/finally behaves + + Synchronous example: + + ```js + findAuthor() { + if (Math.random() > 0.5) { + throw new Error(); + } + return new Author(); + } + + try { + return findAuthor(); // succeed or fail + } catch(error) { + return findOtherAuther(); + } finally { + // always runs + // doesn't affect the return value + } + ``` + + Asynchronous example: + + ```js + findAuthor().catch(function(reason){ + return findOtherAuther(); + }).finally(function(){ + // author was either found, or not + }); + ``` + + @method finally + @param {Function} callback + @return {Promise} + */ + + }, { + key: 'finally', + value: function _finally(callback) { + var promise = this; + var constructor = promise.constructor; + + if (isFunction(callback)) { + return promise.then(function (value) { + return constructor.resolve(callback()).then(function () { + return value; + }); + }, function (reason) { + return constructor.resolve(callback()).then(function () { + throw reason; + }); + }); + } + + return promise.then(callback, callback); + } + }]); + return Promise; + }(); + + Promise$2.prototype.then = then; + Promise$2.all = all; + Promise$2.race = race; + Promise$2.resolve = resolve$1; + Promise$2.reject = reject$1; + Promise$2._setScheduler = setScheduler; + Promise$2._setAsap = setAsap; + Promise$2._asap = asap; + + /*global self*/ + function polyfill() { + var local = void 0; + + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + + var P = local.Promise; + + if (P) { + var promiseToString = null; + try { + promiseToString = Object.prototype.toString.call(P.resolve()); + } catch (e) { + // silently ignored + } + + if (promiseToString === '[object Promise]' && !P.cast) { + return; + } + } + + local.Promise = Promise$2; + } + + // Strange compat.. + Promise$2.polyfill = polyfill; + Promise$2.Promise = Promise$2; + + var Promise$1 = typeof Promise !== "undefined" ? Promise : Promise$2; + + // Register logging callbacks + function registerLoggingCallbacks(obj) { + var i, + l, + key, + callbackNames = ["begin", "done", "log", "testStart", "testDone", "moduleStart", "moduleDone"]; + + function registerLoggingCallback(key) { + var loggingCallback = function loggingCallback(callback) { + if (objectType(callback) !== "function") { + throw new Error("QUnit logging methods require a callback function as their first parameters."); + } + + config.callbacks[key].push(callback); + }; + + return loggingCallback; + } + + for (i = 0, l = callbackNames.length; i < l; i++) { + key = callbackNames[i]; + + // Initialize key collection of logging callback + if (objectType(config.callbacks[key]) === "undefined") { + config.callbacks[key] = []; + } + + obj[key] = registerLoggingCallback(key); + } + } + + function runLoggingCallbacks(key, args) { + var callbacks = config.callbacks[key]; + + // Handling 'log' callbacks separately. Unlike the other callbacks, + // the log callback is not controlled by the processing queue, + // but rather used by asserts. Hence to promisfy the 'log' callback + // would mean promisfying each step of a test + if (key === "log") { + callbacks.map(function (callback) { + return callback(args); + }); + return; + } + + // ensure that each callback is executed serially + return callbacks.reduce(function (promiseChain, callback) { + return promiseChain.then(function () { + return Promise$1.resolve(callback(args)); + }); + }, Promise$1.resolve([])); + } + + // Doesn't support IE9, it will return undefined on these browsers + // See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack + var fileName = (sourceFromStacktrace(0) || "").replace(/(:\d+)+\)?/, "").replace(/.+\//, ""); + + function extractStacktrace(e, offset) { + offset = offset === undefined ? 4 : offset; + + var stack, include, i; + + if (e && e.stack) { + stack = e.stack.split("\n"); + if (/^error$/i.test(stack[0])) { + stack.shift(); + } + if (fileName) { + include = []; + for (i = offset; i < stack.length; i++) { + if (stack[i].indexOf(fileName) !== -1) { + break; + } + include.push(stack[i]); + } + if (include.length) { + return include.join("\n"); + } + } + return stack[offset]; + } + } + + function sourceFromStacktrace(offset) { + var error = new Error(); + + // Support: Safari <=7 only, IE <=10 - 11 only + // Not all browsers generate the `stack` property for `new Error()`, see also #636 + if (!error.stack) { + try { + throw error; + } catch (err) { + error = err; + } + } + + return extractStacktrace(error, offset); + } + + var priorityCount = 0; + var unitSampler = void 0; + + // This is a queue of functions that are tasks within a single test. + // After tests are dequeued from config.queue they are expanded into + // a set of tasks in this queue. + var taskQueue = []; + + /** + * Advances the taskQueue to the next task. If the taskQueue is empty, + * process the testQueue + */ + function advance() { + advanceTaskQueue(); + + if (!taskQueue.length && !config.blocking && !config.current) { + advanceTestQueue(); + } + } + + /** + * Advances the taskQueue with an increased depth + */ + function advanceTaskQueue() { + var start = now(); + config.depth = (config.depth || 0) + 1; + + processTaskQueue(start); + + config.depth--; + } + + /** + * Process the first task on the taskQueue as a promise. + * Each task is a function returned by https://github.com/qunitjs/qunit/blob/master/src/test.js#L381 + */ + function processTaskQueue(start) { + if (taskQueue.length && !config.blocking) { + var elapsedTime = now() - start; + + if (!defined.setTimeout || config.updateRate <= 0 || elapsedTime < config.updateRate) { + var task = taskQueue.shift(); + Promise$1.resolve(task()).then(function () { + if (!taskQueue.length) { + advance(); + } else { + processTaskQueue(start); + } + }); + } else { + setTimeout$1(advance); + } + } + } + + /** + * Advance the testQueue to the next test to process. Call done() if testQueue completes. + */ + function advanceTestQueue() { + if (!config.blocking && !config.queue.length && config.depth === 0) { + done(); + return; + } + + var testTasks = config.queue.shift(); + addToTaskQueue(testTasks()); + + if (priorityCount > 0) { + priorityCount--; + } + + advance(); + } + + /** + * Enqueue the tasks for a test into the task queue. + * @param {Array} tasksArray + */ + function addToTaskQueue(tasksArray) { + taskQueue.push.apply(taskQueue, toConsumableArray(tasksArray)); + } + + /** + * Return the number of tasks remaining in the task queue to be processed. + * @return {Number} + */ + function taskQueueLength() { + return taskQueue.length; + } + + /** + * Adds a test to the TestQueue for execution. + * @param {Function} testTasksFunc + * @param {Boolean} prioritize + * @param {String} seed + */ + function addToTestQueue(testTasksFunc, prioritize, seed) { + if (prioritize) { + config.queue.splice(priorityCount++, 0, testTasksFunc); + } else if (seed) { + if (!unitSampler) { + unitSampler = unitSamplerGenerator(seed); + } + + // Insert into a random position after all prioritized items + var index = Math.floor(unitSampler() * (config.queue.length - priorityCount + 1)); + config.queue.splice(priorityCount + index, 0, testTasksFunc); + } else { + config.queue.push(testTasksFunc); + } + } + + /** + * Creates a seeded "sample" generator which is used for randomizing tests. + */ + function unitSamplerGenerator(seed) { + + // 32-bit xorshift, requires only a nonzero seed + // http://excamera.com/sphinx/article-xorshift.html + var sample = parseInt(generateHash(seed), 16) || -1; + return function () { + sample ^= sample << 13; + sample ^= sample >>> 17; + sample ^= sample << 5; + + // ECMAScript has no unsigned number type + if (sample < 0) { + sample += 0x100000000; + } + + return sample / 0x100000000; + }; + } + + /** + * This function is called when the ProcessingQueue is done processing all + * items. It handles emitting the final run events. + */ + function done() { + var storage = config.storage; + + ProcessingQueue.finished = true; + + var runtime = now() - config.started; + var passed = config.stats.all - config.stats.bad; + + if (config.stats.all === 0) { + + if (config.filter && config.filter.length) { + throw new Error("No tests matched the filter \"" + config.filter + "\"."); + } + + if (config.module && config.module.length) { + throw new Error("No tests matched the module \"" + config.module + "\"."); + } + + if (config.moduleId && config.moduleId.length) { + throw new Error("No tests matched the moduleId \"" + config.moduleId + "\"."); + } + + if (config.testId && config.testId.length) { + throw new Error("No tests matched the testId \"" + config.testId + "\"."); + } + + throw new Error("No tests were run."); + } + + emit("runEnd", globalSuite.end(true)); + runLoggingCallbacks("done", { + passed: passed, + failed: config.stats.bad, + total: config.stats.all, + runtime: runtime + }).then(function () { + + // Clear own storage items if all tests passed + if (storage && config.stats.bad === 0) { + for (var i = storage.length - 1; i >= 0; i--) { + var key = storage.key(i); + + if (key.indexOf("qunit-test-") === 0) { + storage.removeItem(key); + } + } + } + }); + } + + var ProcessingQueue = { + finished: false, + add: addToTestQueue, + advance: advance, + taskCount: taskQueueLength + }; + + var TestReport = function () { + function TestReport(name, suite, options) { + classCallCheck(this, TestReport); + + this.name = name; + this.suiteName = suite.name; + this.fullName = suite.fullName.concat(name); + this.runtime = 0; + this.assertions = []; + + this.skipped = !!options.skip; + this.todo = !!options.todo; + + this.valid = options.valid; + + this._startTime = 0; + this._endTime = 0; + + suite.pushTest(this); + } + + createClass(TestReport, [{ + key: "start", + value: function start(recordTime) { + if (recordTime) { + this._startTime = performanceNow(); + if (performance) { + performance.mark("qunit_test_start"); + } + } + + return { + name: this.name, + suiteName: this.suiteName, + fullName: this.fullName.slice() + }; + } + }, { + key: "end", + value: function end(recordTime) { + if (recordTime) { + this._endTime = performanceNow(); + if (performance) { + performance.mark("qunit_test_end"); + + var testName = this.fullName.join(" – "); + + measure("QUnit Test: " + testName, "qunit_test_start", "qunit_test_end"); + } + } + + return extend(this.start(), { + runtime: this.getRuntime(), + status: this.getStatus(), + errors: this.getFailedAssertions(), + assertions: this.getAssertions() + }); + } + }, { + key: "pushAssertion", + value: function pushAssertion(assertion) { + this.assertions.push(assertion); + } + }, { + key: "getRuntime", + value: function getRuntime() { + return this._endTime - this._startTime; + } + }, { + key: "getStatus", + value: function getStatus() { + if (this.skipped) { + return "skipped"; + } + + var testPassed = this.getFailedAssertions().length > 0 ? this.todo : !this.todo; + + if (!testPassed) { + return "failed"; + } else if (this.todo) { + return "todo"; + } else { + return "passed"; + } + } + }, { + key: "getFailedAssertions", + value: function getFailedAssertions() { + return this.assertions.filter(function (assertion) { + return !assertion.passed; + }); + } + }, { + key: "getAssertions", + value: function getAssertions() { + return this.assertions.slice(); + } + + // Remove actual and expected values from assertions. This is to prevent + // leaking memory throughout a test suite. + + }, { + key: "slimAssertions", + value: function slimAssertions() { + this.assertions = this.assertions.map(function (assertion) { + delete assertion.actual; + delete assertion.expected; + return assertion; + }); + } + }]); + return TestReport; + }(); + + var focused$1 = false; + + function Test(settings) { + var i, l; + + ++Test.count; + + this.expected = null; + this.assertions = []; + this.semaphore = 0; + this.module = config.currentModule; + this.stack = sourceFromStacktrace(3); + this.steps = []; + this.timeout = undefined; + + // If a module is skipped, all its tests and the tests of the child suites + // should be treated as skipped even if they are defined as `only` or `todo`. + // As for `todo` module, all its tests will be treated as `todo` except for + // tests defined as `skip` which will be left intact. + // + // So, if a test is defined as `todo` and is inside a skipped module, we should + // then treat that test as if was defined as `skip`. + if (this.module.skip) { + settings.skip = true; + settings.todo = false; + + // Skipped tests should be left intact + } else if (this.module.todo && !settings.skip) { + settings.todo = true; + } + + extend(this, settings); + + this.testReport = new TestReport(settings.testName, this.module.suiteReport, { + todo: settings.todo, + skip: settings.skip, + valid: this.valid() + }); + + // Register unique strings + for (i = 0, l = this.module.tests; i < l.length; i++) { + if (this.module.tests[i].name === this.testName) { + this.testName += " "; + } + } + + this.testId = generateHash(this.module.name, this.testName); + + this.module.tests.push({ + name: this.testName, + testId: this.testId, + skip: !!settings.skip + }); + + if (settings.skip) { + + // Skipped tests will fully ignore any sent callback + this.callback = function () {}; + this.async = false; + this.expected = 0; + } else { + if (typeof this.callback !== "function") { + var method = this.todo ? "todo" : "test"; + + // eslint-disable-next-line max-len + throw new TypeError("You must provide a function as a test callback to QUnit." + method + "(\"" + settings.testName + "\")"); + } + + this.assert = new Assert(this); + } + } + + Test.count = 0; + + function getNotStartedModules(startModule) { + var module = startModule, + modules = []; + + while (module && module.testsRun === 0) { + modules.push(module); + module = module.parentModule; + } + + // The above push modules from the child to the parent + // return a reversed order with the top being the top most parent module + return modules.reverse(); + } + + Test.prototype = { + before: function before() { + var _this = this; + + var module = this.module, + notStartedModules = getNotStartedModules(module); + + // ensure the callbacks are executed serially for each module + var callbackPromises = notStartedModules.reduce(function (promiseChain, startModule) { + return promiseChain.then(function () { + startModule.stats = { all: 0, bad: 0, started: now() }; + emit("suiteStart", startModule.suiteReport.start(true)); + return runLoggingCallbacks("moduleStart", { + name: startModule.name, + tests: startModule.tests + }); + }); + }, Promise$1.resolve([])); + + return callbackPromises.then(function () { + config.current = _this; + + _this.testEnvironment = extend({}, module.testEnvironment); + + _this.started = now(); + emit("testStart", _this.testReport.start(true)); + return runLoggingCallbacks("testStart", { + name: _this.testName, + module: module.name, + testId: _this.testId, + previousFailure: _this.previousFailure + }).then(function () { + if (!config.pollution) { + saveGlobal(); + } + }); + }); + }, + + run: function run() { + var promise; + + config.current = this; + + this.callbackStarted = now(); + + if (config.notrycatch) { + runTest(this); + return; + } + + try { + runTest(this); + } catch (e) { + this.pushFailure("Died on test #" + (this.assertions.length + 1) + " " + this.stack + ": " + (e.message || e), extractStacktrace(e, 0)); + + // Else next test will carry the responsibility + saveGlobal(); + + // Restart the tests if they're blocking + if (config.blocking) { + internalRecover(this); + } + } + + function runTest(test) { + promise = test.callback.call(test.testEnvironment, test.assert); + test.resolvePromise(promise); + + // If the test has a "lock" on it, but the timeout is 0, then we push a + // failure as the test should be synchronous. + if (test.timeout === 0 && test.semaphore !== 0) { + pushFailure("Test did not finish synchronously even though assert.timeout( 0 ) was used.", sourceFromStacktrace(2)); + } + } + }, + + after: function after() { + checkPollution(); + }, + + queueHook: function queueHook(hook, hookName, hookOwner) { + var _this2 = this; + + var callHook = function callHook() { + var promise = hook.call(_this2.testEnvironment, _this2.assert); + _this2.resolvePromise(promise, hookName); + }; + + var runHook = function runHook() { + if (hookName === "before") { + if (hookOwner.unskippedTestsRun !== 0) { + return; + } + + _this2.preserveEnvironment = true; + } + + // The 'after' hook should only execute when there are not tests left and + // when the 'after' and 'finish' tasks are the only tasks left to process + if (hookName === "after" && hookOwner.unskippedTestsRun !== numberOfUnskippedTests(hookOwner) - 1 && (config.queue.length > 0 || ProcessingQueue.taskCount() > 2)) { + return; + } + + config.current = _this2; + if (config.notrycatch) { + callHook(); + return; + } + try { + callHook(); + } catch (error) { + _this2.pushFailure(hookName + " failed on " + _this2.testName + ": " + (error.message || error), extractStacktrace(error, 0)); + } + }; + + return runHook; + }, + + + // Currently only used for module level hooks, can be used to add global level ones + hooks: function hooks(handler) { + var hooks = []; + + function processHooks(test, module) { + if (module.parentModule) { + processHooks(test, module.parentModule); + } + + if (module.hooks[handler].length) { + for (var i = 0; i < module.hooks[handler].length; i++) { + hooks.push(test.queueHook(module.hooks[handler][i], handler, module)); + } + } + } + + // Hooks are ignored on skipped tests + if (!this.skip) { + processHooks(this, this.module); + } + + return hooks; + }, + + + finish: function finish() { + config.current = this; + + // Release the test callback to ensure that anything referenced has been + // released to be garbage collected. + this.callback = undefined; + + if (this.steps.length) { + var stepsList = this.steps.join(", "); + this.pushFailure("Expected assert.verifySteps() to be called before end of test " + ("after using assert.step(). Unverified steps: " + stepsList), this.stack); + } + + if (config.requireExpects && this.expected === null) { + this.pushFailure("Expected number of assertions to be defined, but expect() was " + "not called.", this.stack); + } else if (this.expected !== null && this.expected !== this.assertions.length) { + this.pushFailure("Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack); + } else if (this.expected === null && !this.assertions.length) { + this.pushFailure("Expected at least one assertion, but none were run - call " + "expect(0) to accept zero assertions.", this.stack); + } + + var i, + module = this.module, + moduleName = module.name, + testName = this.testName, + skipped = !!this.skip, + todo = !!this.todo, + bad = 0, + storage = config.storage; + + this.runtime = now() - this.started; + + config.stats.all += this.assertions.length; + module.stats.all += this.assertions.length; + + for (i = 0; i < this.assertions.length; i++) { + if (!this.assertions[i].result) { + bad++; + config.stats.bad++; + module.stats.bad++; + } + } + + notifyTestsRan(module, skipped); + + // Store result when possible + if (storage) { + if (bad) { + storage.setItem("qunit-test-" + moduleName + "-" + testName, bad); + } else { + storage.removeItem("qunit-test-" + moduleName + "-" + testName); + } + } + + // After emitting the js-reporters event we cleanup the assertion data to + // avoid leaking it. It is not used by the legacy testDone callbacks. + emit("testEnd", this.testReport.end(true)); + this.testReport.slimAssertions(); + + return runLoggingCallbacks("testDone", { + name: testName, + module: moduleName, + skipped: skipped, + todo: todo, + failed: bad, + passed: this.assertions.length - bad, + total: this.assertions.length, + runtime: skipped ? 0 : this.runtime, + + // HTML Reporter use + assertions: this.assertions, + testId: this.testId, + + // Source of Test + source: this.stack + }).then(function () { + if (module.testsRun === numberOfTests(module)) { + var completedModules = [module]; + + // Check if the parent modules, iteratively, are done. If that the case, + // we emit the `suiteEnd` event and trigger `moduleDone` callback. + var parent = module.parentModule; + while (parent && parent.testsRun === numberOfTests(parent)) { + completedModules.push(parent); + parent = parent.parentModule; + } + + return completedModules.reduce(function (promiseChain, completedModule) { + return promiseChain.then(function () { + return logSuiteEnd(completedModule); + }); + }, Promise$1.resolve([])); + } + }).then(function () { + config.current = undefined; + }); + + function logSuiteEnd(module) { + + // Reset `module.hooks` to ensure that anything referenced in these hooks + // has been released to be garbage collected. + module.hooks = {}; + + emit("suiteEnd", module.suiteReport.end(true)); + return runLoggingCallbacks("moduleDone", { + name: module.name, + tests: module.tests, + failed: module.stats.bad, + passed: module.stats.all - module.stats.bad, + total: module.stats.all, + runtime: now() - module.stats.started + }); + } + }, + + preserveTestEnvironment: function preserveTestEnvironment() { + if (this.preserveEnvironment) { + this.module.testEnvironment = this.testEnvironment; + this.testEnvironment = extend({}, this.module.testEnvironment); + } + }, + + queue: function queue() { + var test = this; + + if (!this.valid()) { + return; + } + + function runTest() { + return [function () { + return test.before(); + }].concat(toConsumableArray(test.hooks("before")), [function () { + test.preserveTestEnvironment(); + }], toConsumableArray(test.hooks("beforeEach")), [function () { + test.run(); + }], toConsumableArray(test.hooks("afterEach").reverse()), toConsumableArray(test.hooks("after").reverse()), [function () { + test.after(); + }, function () { + return test.finish(); + }]); + } + + var previousFailCount = config.storage && +config.storage.getItem("qunit-test-" + this.module.name + "-" + this.testName); + + // Prioritize previously failed tests, detected from storage + var prioritize = config.reorder && !!previousFailCount; + + this.previousFailure = !!previousFailCount; + + ProcessingQueue.add(runTest, prioritize, config.seed); + + // If the queue has already finished, we manually process the new test + if (ProcessingQueue.finished) { + ProcessingQueue.advance(); + } + }, + + + pushResult: function pushResult(resultInfo) { + if (this !== config.current) { + throw new Error("Assertion occurred after test had finished."); + } + + // Destructure of resultInfo = { result, actual, expected, message, negative } + var source, + details = { + module: this.module.name, + name: this.testName, + result: resultInfo.result, + message: resultInfo.message, + actual: resultInfo.actual, + testId: this.testId, + negative: resultInfo.negative || false, + runtime: now() - this.started, + todo: !!this.todo + }; + + if (hasOwn.call(resultInfo, "expected")) { + details.expected = resultInfo.expected; + } + + if (!resultInfo.result) { + source = resultInfo.source || sourceFromStacktrace(); + + if (source) { + details.source = source; + } + } + + this.logAssertion(details); + + this.assertions.push({ + result: !!resultInfo.result, + message: resultInfo.message + }); + }, + + pushFailure: function pushFailure(message, source, actual) { + if (!(this instanceof Test)) { + throw new Error("pushFailure() assertion outside test context, was " + sourceFromStacktrace(2)); + } + + this.pushResult({ + result: false, + message: message || "error", + actual: actual || null, + source: source + }); + }, + + /** + * Log assertion details using both the old QUnit.log interface and + * QUnit.on( "assertion" ) interface. + * + * @private + */ + logAssertion: function logAssertion(details) { + runLoggingCallbacks("log", details); + + var assertion = { + passed: details.result, + actual: details.actual, + expected: details.expected, + message: details.message, + stack: details.source, + todo: details.todo + }; + this.testReport.pushAssertion(assertion); + emit("assertion", assertion); + }, + + + resolvePromise: function resolvePromise(promise, phase) { + var then, + resume, + message, + test = this; + if (promise != null) { + then = promise.then; + if (objectType(then) === "function") { + resume = internalStop(test); + if (config.notrycatch) { + then.call(promise, function () { + resume(); + }); + } else { + then.call(promise, function () { + resume(); + }, function (error) { + message = "Promise rejected " + (!phase ? "during" : phase.replace(/Each$/, "")) + " \"" + test.testName + "\": " + (error && error.message || error); + test.pushFailure(message, extractStacktrace(error, 0)); + + // Else next test will carry the responsibility + saveGlobal(); + + // Unblock + internalRecover(test); + }); + } + } + } + }, + + valid: function valid() { + var filter = config.filter, + regexFilter = /^(!?)\/([\w\W]*)\/(i?$)/.exec(filter), + module = config.module && config.module.toLowerCase(), + fullName = this.module.name + ": " + this.testName; + + function moduleChainNameMatch(testModule) { + var testModuleName = testModule.name ? testModule.name.toLowerCase() : null; + if (testModuleName === module) { + return true; + } else if (testModule.parentModule) { + return moduleChainNameMatch(testModule.parentModule); + } else { + return false; + } + } + + function moduleChainIdMatch(testModule) { + return inArray(testModule.moduleId, config.moduleId) || testModule.parentModule && moduleChainIdMatch(testModule.parentModule); + } + + // Internally-generated tests are always valid + if (this.callback && this.callback.validTest) { + return true; + } + + if (config.moduleId && config.moduleId.length > 0 && !moduleChainIdMatch(this.module)) { + + return false; + } + + if (config.testId && config.testId.length > 0 && !inArray(this.testId, config.testId)) { + + return false; + } + + if (module && !moduleChainNameMatch(this.module)) { + return false; + } + + if (!filter) { + return true; + } + + return regexFilter ? this.regexFilter(!!regexFilter[1], regexFilter[2], regexFilter[3], fullName) : this.stringFilter(filter, fullName); + }, + + regexFilter: function regexFilter(exclude, pattern, flags, fullName) { + var regex = new RegExp(pattern, flags); + var match = regex.test(fullName); + + return match !== exclude; + }, + + stringFilter: function stringFilter(filter, fullName) { + filter = filter.toLowerCase(); + fullName = fullName.toLowerCase(); + + var include = filter.charAt(0) !== "!"; + if (!include) { + filter = filter.slice(1); + } + + // If the filter matches, we need to honour include + if (fullName.indexOf(filter) !== -1) { + return include; + } + + // Otherwise, do the opposite + return !include; + } + }; + + function pushFailure() { + if (!config.current) { + throw new Error("pushFailure() assertion outside test context, in " + sourceFromStacktrace(2)); + } + + // Gets current test obj + var currentTest = config.current; + + return currentTest.pushFailure.apply(currentTest, arguments); + } + + function saveGlobal() { + config.pollution = []; + + if (config.noglobals) { + for (var key in global$1) { + if (hasOwn.call(global$1, key)) { + + // In Opera sometimes DOM element ids show up here, ignore them + if (/^qunit-test-output/.test(key)) { + continue; + } + config.pollution.push(key); + } + } + } + } + + function checkPollution() { + var newGlobals, + deletedGlobals, + old = config.pollution; + + saveGlobal(); + + newGlobals = diff(config.pollution, old); + if (newGlobals.length > 0) { + pushFailure("Introduced global variable(s): " + newGlobals.join(", ")); + } + + deletedGlobals = diff(old, config.pollution); + if (deletedGlobals.length > 0) { + pushFailure("Deleted global variable(s): " + deletedGlobals.join(", ")); + } + } + + // Will be exposed as QUnit.test + function test(testName, callback) { + if (focused$1) { + return; + } + + var newTest = new Test({ + testName: testName, + callback: callback + }); + + newTest.queue(); + } + + function todo(testName, callback) { + if (focused$1) { + return; + } + + var newTest = new Test({ + testName: testName, + callback: callback, + todo: true + }); + + newTest.queue(); + } + + // Will be exposed as QUnit.skip + function skip(testName) { + if (focused$1) { + return; + } + + var test = new Test({ + testName: testName, + skip: true + }); + + test.queue(); + } + + // Will be exposed as QUnit.only + function only(testName, callback) { + if (focused$1) { + return; + } + + config.queue.length = 0; + focused$1 = true; + + var newTest = new Test({ + testName: testName, + callback: callback + }); + + newTest.queue(); + } + + // Put a hold on processing and return a function that will release it. + function internalStop(test) { + var released = false; + test.semaphore += 1; + config.blocking = true; + + // Set a recovery timeout, if so configured. + if (defined.setTimeout) { + var timeoutDuration = void 0; + + if (typeof test.timeout === "number") { + timeoutDuration = test.timeout; + } else if (typeof config.testTimeout === "number") { + timeoutDuration = config.testTimeout; + } + + if (typeof timeoutDuration === "number" && timeoutDuration > 0) { + clearTimeout(config.timeout); + config.timeout = setTimeout$1(function () { + pushFailure("Test took longer than " + timeoutDuration + "ms; test timed out.", sourceFromStacktrace(2)); + released = true; + internalRecover(test); + }, timeoutDuration); + } + } + + return function resume() { + if (released) { + return; + } + + released = true; + test.semaphore -= 1; + internalStart(test); + }; + } + + // Forcefully release all processing holds. + function internalRecover(test) { + test.semaphore = 0; + internalStart(test); + } + + // Release a processing hold, scheduling a resumption attempt if no holds remain. + function internalStart(test) { + + // If semaphore is non-numeric, throw error + if (isNaN(test.semaphore)) { + test.semaphore = 0; + + pushFailure("Invalid value on test.semaphore", sourceFromStacktrace(2)); + return; + } + + // Don't start until equal number of stop-calls + if (test.semaphore > 0) { + return; + } + + // Throw an Error if start is called more often than stop + if (test.semaphore < 0) { + test.semaphore = 0; + + pushFailure("Tried to restart test while already started (test's semaphore was 0 already)", sourceFromStacktrace(2)); + return; + } + + // Add a slight delay to allow more assertions etc. + if (defined.setTimeout) { + if (config.timeout) { + clearTimeout(config.timeout); + } + config.timeout = setTimeout$1(function () { + if (test.semaphore > 0) { + return; + } + + if (config.timeout) { + clearTimeout(config.timeout); + } + + begin(); + }); + } else { + begin(); + } + } + + function collectTests(module) { + var tests = [].concat(module.tests); + var modules = [].concat(toConsumableArray(module.childModules)); + + // Do a breadth-first traversal of the child modules + while (modules.length) { + var nextModule = modules.shift(); + tests.push.apply(tests, nextModule.tests); + modules.push.apply(modules, toConsumableArray(nextModule.childModules)); + } + + return tests; + } + + function numberOfTests(module) { + return collectTests(module).length; + } + + function numberOfUnskippedTests(module) { + return collectTests(module).filter(function (test) { + return !test.skip; + }).length; + } + + function notifyTestsRan(module, skipped) { + module.testsRun++; + if (!skipped) { + module.unskippedTestsRun++; + } + while (module = module.parentModule) { + module.testsRun++; + if (!skipped) { + module.unskippedTestsRun++; + } + } + } + + var Assert = function () { + function Assert(testContext) { + classCallCheck(this, Assert); + + this.test = testContext; + } + + // Assert helpers + + createClass(Assert, [{ + key: "timeout", + value: function timeout(duration) { + if (typeof duration !== "number") { + throw new Error("You must pass a number as the duration to assert.timeout"); + } + + this.test.timeout = duration; + } + + // Documents a "step", which is a string value, in a test as a passing assertion + + }, { + key: "step", + value: function step(message) { + var assertionMessage = message; + var result = !!message; + + this.test.steps.push(message); + + if (objectType(message) === "undefined" || message === "") { + assertionMessage = "You must provide a message to assert.step"; + } else if (objectType(message) !== "string") { + assertionMessage = "You must provide a string value to assert.step"; + result = false; + } + + this.pushResult({ + result: result, + message: assertionMessage + }); + } + + // Verifies the steps in a test match a given array of string values + + }, { + key: "verifySteps", + value: function verifySteps(steps, message) { + + // Since the steps array is just string values, we can clone with slice + var actualStepsClone = this.test.steps.slice(); + this.deepEqual(actualStepsClone, steps, message); + this.test.steps.length = 0; + } + + // Specify the number of expected assertions to guarantee that failed test + // (no assertions are run at all) don't slip through. + + }, { + key: "expect", + value: function expect(asserts) { + if (arguments.length === 1) { + this.test.expected = asserts; + } else { + return this.test.expected; + } + } + + // Put a hold on processing and return a function that will release it a maximum of once. + + }, { + key: "async", + value: function async(count) { + var test$$1 = this.test; + + var popped = false, + acceptCallCount = count; + + if (typeof acceptCallCount === "undefined") { + acceptCallCount = 1; + } + + var resume = internalStop(test$$1); + + return function done() { + if (config.current !== test$$1) { + throw Error("assert.async callback called after test finished."); + } + + if (popped) { + test$$1.pushFailure("Too many calls to the `assert.async` callback", sourceFromStacktrace(2)); + return; + } + + acceptCallCount -= 1; + if (acceptCallCount > 0) { + return; + } + + popped = true; + resume(); + }; + } + + // Exports test.push() to the user API + // Alias of pushResult. + + }, { + key: "push", + value: function push(result, actual, expected, message, negative) { + Logger.warn("assert.push is deprecated and will be removed in QUnit 3.0." + " Please use assert.pushResult instead (https://api.qunitjs.com/assert/pushResult)."); + + var currentAssert = this instanceof Assert ? this : config.current.assert; + return currentAssert.pushResult({ + result: result, + actual: actual, + expected: expected, + message: message, + negative: negative + }); + } + }, { + key: "pushResult", + value: function pushResult(resultInfo) { + + // Destructure of resultInfo = { result, actual, expected, message, negative } + var assert = this; + var currentTest = assert instanceof Assert && assert.test || config.current; + + // Backwards compatibility fix. + // Allows the direct use of global exported assertions and QUnit.assert.* + // Although, it's use is not recommended as it can leak assertions + // to other tests from async tests, because we only get a reference to the current test, + // not exactly the test where assertion were intended to be called. + if (!currentTest) { + throw new Error("assertion outside test context, in " + sourceFromStacktrace(2)); + } + + if (!(assert instanceof Assert)) { + assert = currentTest.assert; + } + + return assert.test.pushResult(resultInfo); + } + }, { + key: "ok", + value: function ok(result, message) { + if (!message) { + message = result ? "okay" : "failed, expected argument to be truthy, was: " + dump.parse(result); + } + + this.pushResult({ + result: !!result, + actual: result, + expected: true, + message: message + }); + } + }, { + key: "notOk", + value: function notOk(result, message) { + if (!message) { + message = !result ? "okay" : "failed, expected argument to be falsy, was: " + dump.parse(result); + } + + this.pushResult({ + result: !result, + actual: result, + expected: false, + message: message + }); + } + }, { + key: "equal", + value: function equal(actual, expected, message) { + + // eslint-disable-next-line eqeqeq + var result = expected == actual; + + this.pushResult({ + result: result, + actual: actual, + expected: expected, + message: message + }); + } + }, { + key: "notEqual", + value: function notEqual(actual, expected, message) { + + // eslint-disable-next-line eqeqeq + var result = expected != actual; + + this.pushResult({ + result: result, + actual: actual, + expected: expected, + message: message, + negative: true + }); + } + }, { + key: "propEqual", + value: function propEqual(actual, expected, message) { + actual = objectValues(actual); + expected = objectValues(expected); + + this.pushResult({ + result: equiv(actual, expected), + actual: actual, + expected: expected, + message: message + }); + } + }, { + key: "notPropEqual", + value: function notPropEqual(actual, expected, message) { + actual = objectValues(actual); + expected = objectValues(expected); + + this.pushResult({ + result: !equiv(actual, expected), + actual: actual, + expected: expected, + message: message, + negative: true + }); + } + }, { + key: "deepEqual", + value: function deepEqual(actual, expected, message) { + this.pushResult({ + result: equiv(actual, expected), + actual: actual, + expected: expected, + message: message + }); + } + }, { + key: "notDeepEqual", + value: function notDeepEqual(actual, expected, message) { + this.pushResult({ + result: !equiv(actual, expected), + actual: actual, + expected: expected, + message: message, + negative: true + }); + } + }, { + key: "strictEqual", + value: function strictEqual(actual, expected, message) { + this.pushResult({ + result: expected === actual, + actual: actual, + expected: expected, + message: message + }); + } + }, { + key: "notStrictEqual", + value: function notStrictEqual(actual, expected, message) { + this.pushResult({ + result: expected !== actual, + actual: actual, + expected: expected, + message: message, + negative: true + }); + } + }, { + key: "throws", + value: function throws(block, expected, message) { + var actual = void 0, + result = false; + + var currentTest = this instanceof Assert && this.test || config.current; + + // 'expected' is optional unless doing string comparison + if (objectType(expected) === "string") { + if (message == null) { + message = expected; + expected = null; + } else { + throw new Error("throws/raises does not accept a string value for the expected argument.\n" + "Use a non-string object value (e.g. regExp) instead if it's necessary."); + } + } + + currentTest.ignoreGlobalErrors = true; + try { + block.call(currentTest.testEnvironment); + } catch (e) { + actual = e; + } + currentTest.ignoreGlobalErrors = false; + + if (actual) { + var expectedType = objectType(expected); + + // We don't want to validate thrown error + if (!expected) { + result = true; + + // Expected is a regexp + } else if (expectedType === "regexp") { + result = expected.test(errorString(actual)); + + // Log the string form of the regexp + expected = String(expected); + + // Expected is a constructor, maybe an Error constructor + } else if (expectedType === "function" && actual instanceof expected) { + result = true; + + // Expected is an Error object + } else if (expectedType === "object") { + result = actual instanceof expected.constructor && actual.name === expected.name && actual.message === expected.message; + + // Log the string form of the Error object + expected = errorString(expected); + + // Expected is a validation function which returns true if validation passed + } else if (expectedType === "function" && expected.call({}, actual) === true) { + expected = null; + result = true; + } + } + + currentTest.assert.pushResult({ + result: result, + + // undefined if it didn't throw + actual: actual && errorString(actual), + expected: expected, + message: message + }); + } + }, { + key: "rejects", + value: function rejects(promise, expected, message) { + var result = false; + + var currentTest = this instanceof Assert && this.test || config.current; + + // 'expected' is optional unless doing string comparison + if (objectType(expected) === "string") { + if (message === undefined) { + message = expected; + expected = undefined; + } else { + message = "assert.rejects does not accept a string value for the expected " + "argument.\nUse a non-string object value (e.g. validator function) instead " + "if necessary."; + + currentTest.assert.pushResult({ + result: false, + message: message + }); + + return; + } + } + + var then = promise && promise.then; + if (objectType(then) !== "function") { + var _message = "The value provided to `assert.rejects` in " + "\"" + currentTest.testName + "\" was not a promise."; + + currentTest.assert.pushResult({ + result: false, + message: _message, + actual: promise + }); + + return; + } + + var done = this.async(); + + return then.call(promise, function handleFulfillment() { + var message = "The promise returned by the `assert.rejects` callback in " + "\"" + currentTest.testName + "\" did not reject."; + + currentTest.assert.pushResult({ + result: false, + message: message, + actual: promise + }); + + done(); + }, function handleRejection(actual) { + var expectedType = objectType(expected); + + // We don't want to validate + if (expected === undefined) { + result = true; + + // Expected is a regexp + } else if (expectedType === "regexp") { + result = expected.test(errorString(actual)); + + // Log the string form of the regexp + expected = String(expected); + + // Expected is a constructor, maybe an Error constructor + } else if (expectedType === "function" && actual instanceof expected) { + result = true; + + // Expected is an Error object + } else if (expectedType === "object") { + result = actual instanceof expected.constructor && actual.name === expected.name && actual.message === expected.message; + + // Log the string form of the Error object + expected = errorString(expected); + + // Expected is a validation function which returns true if validation passed + } else { + if (expectedType === "function") { + result = expected.call({}, actual) === true; + expected = null; + + // Expected is some other invalid type + } else { + result = false; + message = "invalid expected value provided to `assert.rejects` " + "callback in \"" + currentTest.testName + "\": " + expectedType + "."; + } + } + + currentTest.assert.pushResult({ + result: result, + + // leave rejection value of undefined as-is + actual: actual && errorString(actual), + expected: expected, + message: message + }); + + done(); + }); + } + }]); + return Assert; + }(); + + // Provide an alternative to assert.throws(), for environments that consider throws a reserved word + // Known to us are: Closure Compiler, Narwhal + // eslint-disable-next-line dot-notation + + + Assert.prototype.raises = Assert.prototype["throws"]; + + /** + * Converts an error into a simple string for comparisons. + * + * @param {Error|Object} error + * @return {String} + */ + function errorString(error) { + var resultErrorString = error.toString(); + + // If the error wasn't a subclass of Error but something like + // an object literal with name and message properties... + if (resultErrorString.substring(0, 7) === "[object") { + var name = error.name ? error.name.toString() : "Error"; + var message = error.message ? error.message.toString() : ""; + + if (name && message) { + return name + ": " + message; + } else if (name) { + return name; + } else if (message) { + return message; + } else { + return "Error"; + } + } else { + return resultErrorString; + } + } + + /* global module, exports, define */ + function exportQUnit(QUnit) { + + if (defined.document) { + + // QUnit may be defined when it is preconfigured but then only QUnit and QUnit.config may be defined. + if (window$1.QUnit && window$1.QUnit.version) { + throw new Error("QUnit has already been defined."); + } + + window$1.QUnit = QUnit; + } + + // For nodejs + if (typeof module !== "undefined" && module && module.exports) { + module.exports = QUnit; + + // For consistency with CommonJS environments' exports + module.exports.QUnit = QUnit; + } + + // For CommonJS with exports, but without module.exports, like Rhino + if (typeof exports !== "undefined" && exports) { + exports.QUnit = QUnit; + } + + if (typeof define === "function" && define.amd) { + define(function () { + return QUnit; + }); + QUnit.config.autostart = false; + } + + // For Web/Service Workers + if (self$1 && self$1.WorkerGlobalScope && self$1 instanceof self$1.WorkerGlobalScope) { + self$1.QUnit = QUnit; + } + } + + // Handle an unhandled exception. By convention, returns true if further + // error handling should be suppressed and false otherwise. + // In this case, we will only suppress further error handling if the + // "ignoreGlobalErrors" configuration option is enabled. + function onError(error) { + for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + if (config.current) { + if (config.current.ignoreGlobalErrors) { + return true; + } + pushFailure.apply(undefined, [error.message, error.stacktrace || error.fileName + ":" + error.lineNumber].concat(args)); + } else { + test("global failure", extend(function () { + pushFailure.apply(undefined, [error.message, error.stacktrace || error.fileName + ":" + error.lineNumber].concat(args)); + }, { validTest: true })); + } + + return false; + } + + // Handle an unhandled rejection + function onUnhandledRejection(reason) { + var resultInfo = { + result: false, + message: reason.message || "error", + actual: reason, + source: reason.stack || sourceFromStacktrace(3) + }; + + var currentTest = config.current; + if (currentTest) { + currentTest.assert.pushResult(resultInfo); + } else { + test("global failure", extend(function (assert) { + assert.pushResult(resultInfo); + }, { validTest: true })); + } + } + + var QUnit = {}; + var globalSuite = new SuiteReport(); + + // The initial "currentModule" represents the global (or top-level) module that + // is not explicitly defined by the user, therefore we add the "globalSuite" to + // it since each module has a suiteReport associated with it. + config.currentModule.suiteReport = globalSuite; + + var globalStartCalled = false; + var runStarted = false; + + // Figure out if we're running the tests from a server or not + QUnit.isLocal = !(defined.document && window$1.location.protocol !== "file:"); + + // Expose the current QUnit version + QUnit.version = "2.9.2"; + + extend(QUnit, { + on: on, + + module: module$1, + + test: test, + + todo: todo, + + skip: skip, + + only: only, + + start: function start(count) { + var globalStartAlreadyCalled = globalStartCalled; + + if (!config.current) { + globalStartCalled = true; + + if (runStarted) { + throw new Error("Called start() while test already started running"); + } else if (globalStartAlreadyCalled || count > 1) { + throw new Error("Called start() outside of a test context too many times"); + } else if (config.autostart) { + throw new Error("Called start() outside of a test context when " + "QUnit.config.autostart was true"); + } else if (!config.pageLoaded) { + + // The page isn't completely loaded yet, so we set autostart and then + // load if we're in Node or wait for the browser's load event. + config.autostart = true; + + // Starts from Node even if .load was not previously called. We still return + // early otherwise we'll wind up "beginning" twice. + if (!defined.document) { + QUnit.load(); + } + + return; + } + } else { + throw new Error("QUnit.start cannot be called inside a test context."); + } + + scheduleBegin(); + }, + + config: config, + + is: is, + + objectType: objectType, + + extend: extend, + + load: function load() { + config.pageLoaded = true; + + // Initialize the configuration options + extend(config, { + stats: { all: 0, bad: 0 }, + started: 0, + updateRate: 1000, + autostart: true, + filter: "" + }, true); + + if (!runStarted) { + config.blocking = false; + + if (config.autostart) { + scheduleBegin(); + } + } + }, + + stack: function stack(offset) { + offset = (offset || 0) + 2; + return sourceFromStacktrace(offset); + }, + + onError: onError, + + onUnhandledRejection: onUnhandledRejection + }); + + QUnit.pushFailure = pushFailure; + QUnit.assert = Assert.prototype; + QUnit.equiv = equiv; + QUnit.dump = dump; + + registerLoggingCallbacks(QUnit); + + function scheduleBegin() { + + runStarted = true; + + // Add a slight delay to allow definition of more modules and tests. + if (defined.setTimeout) { + setTimeout$1(function () { + begin(); + }); + } else { + begin(); + } + } + + function unblockAndAdvanceQueue() { + config.blocking = false; + ProcessingQueue.advance(); + } + + function begin() { + var i, + l, + modulesLog = []; + + // If the test run hasn't officially begun yet + if (!config.started) { + + // Record the time of the test run's beginning + config.started = now(); + + // Delete the loose unnamed module if unused. + if (config.modules[0].name === "" && config.modules[0].tests.length === 0) { + config.modules.shift(); + } + + // Avoid unnecessary information by not logging modules' test environments + for (i = 0, l = config.modules.length; i < l; i++) { + modulesLog.push({ + name: config.modules[i].name, + tests: config.modules[i].tests + }); + } + + // The test run is officially beginning now + emit("runStart", globalSuite.start(true)); + runLoggingCallbacks("begin", { + totalTests: Test.count, + modules: modulesLog + }).then(unblockAndAdvanceQueue); + } else { + unblockAndAdvanceQueue(); + } + } + + exportQUnit(QUnit); + + (function () { + + if (typeof window$1 === "undefined" || typeof document$1 === "undefined") { + return; + } + + var config = QUnit.config, + hasOwn = Object.prototype.hasOwnProperty; + + // Stores fixture HTML for resetting later + function storeFixture() { + + // Avoid overwriting user-defined values + if (hasOwn.call(config, "fixture")) { + return; + } + + var fixture = document$1.getElementById("qunit-fixture"); + if (fixture) { + config.fixture = fixture.cloneNode(true); + } + } + + QUnit.begin(storeFixture); + + // Resets the fixture DOM element if available. + function resetFixture() { + if (config.fixture == null) { + return; + } + + var fixture = document$1.getElementById("qunit-fixture"); + var resetFixtureType = _typeof(config.fixture); + if (resetFixtureType === "string") { + + // support user defined values for `config.fixture` + var newFixture = document$1.createElement("div"); + newFixture.setAttribute("id", "qunit-fixture"); + newFixture.innerHTML = config.fixture; + fixture.parentNode.replaceChild(newFixture, fixture); + } else { + var clonedFixture = config.fixture.cloneNode(true); + fixture.parentNode.replaceChild(clonedFixture, fixture); + } + } + + QUnit.testStart(resetFixture); + })(); + + (function () { + + // Only interact with URLs via window.location + var location = typeof window$1 !== "undefined" && window$1.location; + if (!location) { + return; + } + + var urlParams = getUrlParams(); + + QUnit.urlParams = urlParams; + + // Match module/test by inclusion in an array + QUnit.config.moduleId = [].concat(urlParams.moduleId || []); + QUnit.config.testId = [].concat(urlParams.testId || []); + + // Exact case-insensitive match of the module name + QUnit.config.module = urlParams.module; + + // Regular expression or case-insenstive substring match against "moduleName: testName" + QUnit.config.filter = urlParams.filter; + + // Test order randomization + if (urlParams.seed === true) { + + // Generate a random seed if the option is specified without a value + QUnit.config.seed = Math.random().toString(36).slice(2); + } else if (urlParams.seed) { + QUnit.config.seed = urlParams.seed; + } + + // Add URL-parameter-mapped config values with UI form rendering data + QUnit.config.urlConfig.push({ + id: "hidepassed", + label: "Hide passed tests", + tooltip: "Only show tests and assertions that fail. Stored as query-strings." + }, { + id: "noglobals", + label: "Check for Globals", + tooltip: "Enabling this will test if any test introduces new properties on the " + "global object (`window` in Browsers). Stored as query-strings." + }, { + id: "notrycatch", + label: "No try-catch", + tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging " + "exceptions in IE reasonable. Stored as query-strings." + }); + + QUnit.begin(function () { + var i, + option, + urlConfig = QUnit.config.urlConfig; + + for (i = 0; i < urlConfig.length; i++) { + + // Options can be either strings or objects with nonempty "id" properties + option = QUnit.config.urlConfig[i]; + if (typeof option !== "string") { + option = option.id; + } + + if (QUnit.config[option] === undefined) { + QUnit.config[option] = urlParams[option]; + } + } + }); + + function getUrlParams() { + var i, param, name, value; + var urlParams = Object.create(null); + var params = location.search.slice(1).split("&"); + var length = params.length; + + for (i = 0; i < length; i++) { + if (params[i]) { + param = params[i].split("="); + name = decodeQueryParam(param[0]); + + // Allow just a key to turn on a flag, e.g., test.html?noglobals + value = param.length === 1 || decodeQueryParam(param.slice(1).join("=")); + if (name in urlParams) { + urlParams[name] = [].concat(urlParams[name], value); + } else { + urlParams[name] = value; + } + } + } + + return urlParams; + } + + function decodeQueryParam(param) { + return decodeURIComponent(param.replace(/\+/g, "%20")); + } + })(); + + var stats = { + passedTests: 0, + failedTests: 0, + skippedTests: 0, + todoTests: 0 + }; + + // Escape text for attribute or text content. + function escapeText(s) { + if (!s) { + return ""; + } + s = s + ""; + + // Both single quotes and double quotes (for attributes) + return s.replace(/['"<>&]/g, function (s) { + switch (s) { + case "'": + return "'"; + case "\"": + return """; + case "<": + return "<"; + case ">": + return ">"; + case "&": + return "&"; + } + }); + } + + (function () { + + // Don't load the HTML Reporter on non-browser environments + if (typeof window$1 === "undefined" || !window$1.document) { + return; + } + + var config = QUnit.config, + hiddenTests = [], + document = window$1.document, + collapseNext = false, + hasOwn = Object.prototype.hasOwnProperty, + unfilteredUrl = setUrl({ filter: undefined, module: undefined, + moduleId: undefined, testId: undefined }), + modulesList = []; + + function addEvent(elem, type, fn) { + elem.addEventListener(type, fn, false); + } + + function removeEvent(elem, type, fn) { + elem.removeEventListener(type, fn, false); + } + + function addEvents(elems, type, fn) { + var i = elems.length; + while (i--) { + addEvent(elems[i], type, fn); + } + } + + function hasClass(elem, name) { + return (" " + elem.className + " ").indexOf(" " + name + " ") >= 0; + } + + function addClass(elem, name) { + if (!hasClass(elem, name)) { + elem.className += (elem.className ? " " : "") + name; + } + } + + function toggleClass(elem, name, force) { + if (force || typeof force === "undefined" && !hasClass(elem, name)) { + addClass(elem, name); + } else { + removeClass(elem, name); + } + } + + function removeClass(elem, name) { + var set = " " + elem.className + " "; + + // Class name may appear multiple times + while (set.indexOf(" " + name + " ") >= 0) { + set = set.replace(" " + name + " ", " "); + } + + // Trim for prettiness + elem.className = typeof set.trim === "function" ? set.trim() : set.replace(/^\s+|\s+$/g, ""); + } + + function id(name) { + return document.getElementById && document.getElementById(name); + } + + function abortTests() { + var abortButton = id("qunit-abort-tests-button"); + if (abortButton) { + abortButton.disabled = true; + abortButton.innerHTML = "Aborting..."; + } + QUnit.config.queue.length = 0; + return false; + } + + function interceptNavigation(ev) { + applyUrlParams(); + + if (ev && ev.preventDefault) { + ev.preventDefault(); + } + + return false; + } + + function getUrlConfigHtml() { + var i, + j, + val, + escaped, + escapedTooltip, + selection = false, + urlConfig = config.urlConfig, + urlConfigHtml = ""; + + for (i = 0; i < urlConfig.length; i++) { + + // Options can be either strings or objects with nonempty "id" properties + val = config.urlConfig[i]; + if (typeof val === "string") { + val = { + id: val, + label: val + }; + } + + escaped = escapeText(val.id); + escapedTooltip = escapeText(val.tooltip); + + if (!val.value || typeof val.value === "string") { + urlConfigHtml += ""; + } else { + urlConfigHtml += ""; + } + } + + return urlConfigHtml; + } + + // Handle "click" events on toolbar checkboxes and "change" for select menus. + // Updates the URL with the new state of `config.urlConfig` values. + function toolbarChanged() { + var updatedUrl, + value, + tests, + field = this, + params = {}; + + // Detect if field is a select menu or a checkbox + if ("selectedIndex" in field) { + value = field.options[field.selectedIndex].value || undefined; + } else { + value = field.checked ? field.defaultValue || true : undefined; + } + + params[field.name] = value; + updatedUrl = setUrl(params); + + // Check if we can apply the change without a page refresh + if ("hidepassed" === field.name && "replaceState" in window$1.history) { + QUnit.urlParams[field.name] = value; + config[field.name] = value || false; + tests = id("qunit-tests"); + if (tests) { + var length = tests.children.length; + var children = tests.children; + + if (field.checked) { + for (var i = 0; i < length; i++) { + var test = children[i]; + + if (test && test.className.indexOf("pass") > -1) { + hiddenTests.push(test); + } + } + + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = hiddenTests[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var hiddenTest = _step.value; + + tests.removeChild(hiddenTest); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } else { + while ((test = hiddenTests.pop()) != null) { + tests.appendChild(test); + } + } + } + window$1.history.replaceState(null, "", updatedUrl); + } else { + window$1.location = updatedUrl; + } + } + + function setUrl(params) { + var key, + arrValue, + i, + querystring = "?", + location = window$1.location; + + params = QUnit.extend(QUnit.extend({}, QUnit.urlParams), params); + + for (key in params) { + + // Skip inherited or undefined properties + if (hasOwn.call(params, key) && params[key] !== undefined) { + + // Output a parameter for each value of this key + // (but usually just one) + arrValue = [].concat(params[key]); + for (i = 0; i < arrValue.length; i++) { + querystring += encodeURIComponent(key); + if (arrValue[i] !== true) { + querystring += "=" + encodeURIComponent(arrValue[i]); + } + querystring += "&"; + } + } + } + return location.protocol + "//" + location.host + location.pathname + querystring.slice(0, -1); + } + + function applyUrlParams() { + var i, + selectedModules = [], + modulesList = id("qunit-modulefilter-dropdown-list").getElementsByTagName("input"), + filter = id("qunit-filter-input").value; + + for (i = 0; i < modulesList.length; i++) { + if (modulesList[i].checked) { + selectedModules.push(modulesList[i].value); + } + } + + window$1.location = setUrl({ + filter: filter === "" ? undefined : filter, + moduleId: selectedModules.length === 0 ? undefined : selectedModules, + + // Remove module and testId filter + module: undefined, + testId: undefined + }); + } + + function toolbarUrlConfigContainer() { + var urlConfigContainer = document.createElement("span"); + + urlConfigContainer.innerHTML = getUrlConfigHtml(); + addClass(urlConfigContainer, "qunit-url-config"); + + addEvents(urlConfigContainer.getElementsByTagName("input"), "change", toolbarChanged); + addEvents(urlConfigContainer.getElementsByTagName("select"), "change", toolbarChanged); + + return urlConfigContainer; + } + + function abortTestsButton() { + var button = document.createElement("button"); + button.id = "qunit-abort-tests-button"; + button.innerHTML = "Abort"; + addEvent(button, "click", abortTests); + return button; + } + + function toolbarLooseFilter() { + var filter = document.createElement("form"), + label = document.createElement("label"), + input = document.createElement("input"), + button = document.createElement("button"); + + addClass(filter, "qunit-filter"); + + label.innerHTML = "Filter: "; + + input.type = "text"; + input.value = config.filter || ""; + input.name = "filter"; + input.id = "qunit-filter-input"; + + button.innerHTML = "Go"; + + label.appendChild(input); + + filter.appendChild(label); + filter.appendChild(document.createTextNode(" ")); + filter.appendChild(button); + addEvent(filter, "submit", interceptNavigation); + + return filter; + } + + function moduleListHtml() { + var i, + checked, + html = ""; + + for (i = 0; i < config.modules.length; i++) { + if (config.modules[i].name !== "") { + checked = config.moduleId.indexOf(config.modules[i].moduleId) > -1; + html += "
              1. "; + } + } + + return html; + } + + function toolbarModuleFilter() { + var commit, + reset, + moduleFilter = document.createElement("form"), + label = document.createElement("label"), + moduleSearch = document.createElement("input"), + dropDown = document.createElement("div"), + actions = document.createElement("span"), + applyButton = document.createElement("button"), + resetButton = document.createElement("button"), + allModulesLabel = document.createElement("label"), + allCheckbox = document.createElement("input"), + dropDownList = document.createElement("ul"), + dirty = false; + + moduleSearch.id = "qunit-modulefilter-search"; + moduleSearch.autocomplete = "off"; + addEvent(moduleSearch, "input", searchInput); + addEvent(moduleSearch, "input", searchFocus); + addEvent(moduleSearch, "focus", searchFocus); + addEvent(moduleSearch, "click", searchFocus); + + label.id = "qunit-modulefilter-search-container"; + label.innerHTML = "Module: "; + label.appendChild(moduleSearch); + + applyButton.textContent = "Apply"; + applyButton.style.display = "none"; + + resetButton.textContent = "Reset"; + resetButton.type = "reset"; + resetButton.style.display = "none"; + + allCheckbox.type = "checkbox"; + allCheckbox.checked = config.moduleId.length === 0; + + allModulesLabel.className = "clickable"; + if (config.moduleId.length) { + allModulesLabel.className = "checked"; + } + allModulesLabel.appendChild(allCheckbox); + allModulesLabel.appendChild(document.createTextNode("All modules")); + + actions.id = "qunit-modulefilter-actions"; + actions.appendChild(applyButton); + actions.appendChild(resetButton); + actions.appendChild(allModulesLabel); + commit = actions.firstChild; + reset = commit.nextSibling; + addEvent(commit, "click", applyUrlParams); + + dropDownList.id = "qunit-modulefilter-dropdown-list"; + dropDownList.innerHTML = moduleListHtml(); + + dropDown.id = "qunit-modulefilter-dropdown"; + dropDown.style.display = "none"; + dropDown.appendChild(actions); + dropDown.appendChild(dropDownList); + addEvent(dropDown, "change", selectionChange); + selectionChange(); + + moduleFilter.id = "qunit-modulefilter"; + moduleFilter.appendChild(label); + moduleFilter.appendChild(dropDown); + addEvent(moduleFilter, "submit", interceptNavigation); + addEvent(moduleFilter, "reset", function () { + + // Let the reset happen, then update styles + window$1.setTimeout(selectionChange); + }); + + // Enables show/hide for the dropdown + function searchFocus() { + if (dropDown.style.display !== "none") { + return; + } + + dropDown.style.display = "block"; + addEvent(document, "click", hideHandler); + addEvent(document, "keydown", hideHandler); + + // Hide on Escape keydown or outside-container click + function hideHandler(e) { + var inContainer = moduleFilter.contains(e.target); + + if (e.keyCode === 27 || !inContainer) { + if (e.keyCode === 27 && inContainer) { + moduleSearch.focus(); + } + dropDown.style.display = "none"; + removeEvent(document, "click", hideHandler); + removeEvent(document, "keydown", hideHandler); + moduleSearch.value = ""; + searchInput(); + } + } + } + + // Processes module search box input + function searchInput() { + var i, + item, + searchText = moduleSearch.value.toLowerCase(), + listItems = dropDownList.children; + + for (i = 0; i < listItems.length; i++) { + item = listItems[i]; + if (!searchText || item.textContent.toLowerCase().indexOf(searchText) > -1) { + item.style.display = ""; + } else { + item.style.display = "none"; + } + } + } + + // Processes selection changes + function selectionChange(evt) { + var i, + item, + checkbox = evt && evt.target || allCheckbox, + modulesList = dropDownList.getElementsByTagName("input"), + selectedNames = []; + + toggleClass(checkbox.parentNode, "checked", checkbox.checked); + + dirty = false; + if (checkbox.checked && checkbox !== allCheckbox) { + allCheckbox.checked = false; + removeClass(allCheckbox.parentNode, "checked"); + } + for (i = 0; i < modulesList.length; i++) { + item = modulesList[i]; + if (!evt) { + toggleClass(item.parentNode, "checked", item.checked); + } else if (checkbox === allCheckbox && checkbox.checked) { + item.checked = false; + removeClass(item.parentNode, "checked"); + } + dirty = dirty || item.checked !== item.defaultChecked; + if (item.checked) { + selectedNames.push(item.parentNode.textContent); + } + } + + commit.style.display = reset.style.display = dirty ? "" : "none"; + moduleSearch.placeholder = selectedNames.join(", ") || allCheckbox.parentNode.textContent; + moduleSearch.title = "Type to filter list. Current selection:\n" + (selectedNames.join("\n") || allCheckbox.parentNode.textContent); + } + + return moduleFilter; + } + + function appendToolbar() { + var toolbar = id("qunit-testrunner-toolbar"); + + if (toolbar) { + toolbar.appendChild(toolbarUrlConfigContainer()); + toolbar.appendChild(toolbarModuleFilter()); + toolbar.appendChild(toolbarLooseFilter()); + toolbar.appendChild(document.createElement("div")).className = "clearfix"; + } + } + + function appendHeader() { + var header = id("qunit-header"); + + if (header) { + header.innerHTML = "" + header.innerHTML + " "; + } + } + + function appendBanner() { + var banner = id("qunit-banner"); + + if (banner) { + banner.className = ""; + } + } + + function appendTestResults() { + var tests = id("qunit-tests"), + result = id("qunit-testresult"), + controls; + + if (result) { + result.parentNode.removeChild(result); + } + + if (tests) { + tests.innerHTML = ""; + result = document.createElement("p"); + result.id = "qunit-testresult"; + result.className = "result"; + tests.parentNode.insertBefore(result, tests); + result.innerHTML = "
                Running...
                 
                " + "
                " + "
                "; + controls = id("qunit-testresult-controls"); + } + + if (controls) { + controls.appendChild(abortTestsButton()); + } + } + + function appendFilteredTest() { + var testId = QUnit.config.testId; + if (!testId || testId.length <= 0) { + return ""; + } + return "
                Rerunning selected tests: " + escapeText(testId.join(", ")) + " Run all tests
                "; + } + + function appendUserAgent() { + var userAgent = id("qunit-userAgent"); + + if (userAgent) { + userAgent.innerHTML = ""; + userAgent.appendChild(document.createTextNode("QUnit " + QUnit.version + "; " + navigator.userAgent)); + } + } + + function appendInterface() { + var qunit = id("qunit"); + + if (qunit) { + qunit.innerHTML = "

                " + escapeText(document.title) + "

                " + "

                " + "
                " + appendFilteredTest() + "

                " + "
                  "; + } + + appendHeader(); + appendBanner(); + appendTestResults(); + appendUserAgent(); + appendToolbar(); + } + + function appendTest(name, testId, moduleName) { + var title, + rerunTrigger, + testBlock, + assertList, + tests = id("qunit-tests"); + + if (!tests) { + return; + } + + title = document.createElement("strong"); + title.innerHTML = getNameHtml(name, moduleName); + + rerunTrigger = document.createElement("a"); + rerunTrigger.innerHTML = "Rerun"; + rerunTrigger.href = setUrl({ testId: testId }); + + testBlock = document.createElement("li"); + testBlock.appendChild(title); + testBlock.appendChild(rerunTrigger); + testBlock.id = "qunit-test-output-" + testId; + + assertList = document.createElement("ol"); + assertList.className = "qunit-assert-list"; + + testBlock.appendChild(assertList); + + tests.appendChild(testBlock); + } + + // HTML Reporter initialization and load + QUnit.begin(function (details) { + var i, moduleObj; + + // Sort modules by name for the picker + for (i = 0; i < details.modules.length; i++) { + moduleObj = details.modules[i]; + if (moduleObj.name) { + modulesList.push(moduleObj.name); + } + } + modulesList.sort(function (a, b) { + return a.localeCompare(b); + }); + + // Initialize QUnit elements + appendInterface(); + }); + + QUnit.done(function (details) { + var banner = id("qunit-banner"), + tests = id("qunit-tests"), + abortButton = id("qunit-abort-tests-button"), + totalTests = stats.passedTests + stats.skippedTests + stats.todoTests + stats.failedTests, + html = [totalTests, " tests completed in ", details.runtime, " milliseconds, with ", stats.failedTests, " failed, ", stats.skippedTests, " skipped, and ", stats.todoTests, " todo.
                  ", "", details.passed, " assertions of ", details.total, " passed, ", details.failed, " failed."].join(""), + test, + assertLi, + assertList; + + // Update remaing tests to aborted + if (abortButton && abortButton.disabled) { + html = "Tests aborted after " + details.runtime + " milliseconds."; + + for (var i = 0; i < tests.children.length; i++) { + test = tests.children[i]; + if (test.className === "" || test.className === "running") { + test.className = "aborted"; + assertList = test.getElementsByTagName("ol")[0]; + assertLi = document.createElement("li"); + assertLi.className = "fail"; + assertLi.innerHTML = "Test aborted."; + assertList.appendChild(assertLi); + } + } + } + + if (banner && (!abortButton || abortButton.disabled === false)) { + banner.className = stats.failedTests ? "qunit-fail" : "qunit-pass"; + } + + if (abortButton) { + abortButton.parentNode.removeChild(abortButton); + } + + if (tests) { + id("qunit-testresult-display").innerHTML = html; + } + + if (config.altertitle && document.title) { + + // Show ✖ for good, ✔ for bad suite result in title + // use escape sequences in case file gets loaded with non-utf-8 + // charset + document.title = [stats.failedTests ? "\u2716" : "\u2714", document.title.replace(/^[\u2714\u2716] /i, "")].join(" "); + } + + // Scroll back to top to show results + if (config.scrolltop && window$1.scrollTo) { + window$1.scrollTo(0, 0); + } + }); + + function getNameHtml(name, module) { + var nameHtml = ""; + + if (module) { + nameHtml = "" + escapeText(module) + ": "; + } + + nameHtml += "" + escapeText(name) + ""; + + return nameHtml; + } + + QUnit.testStart(function (details) { + var running, bad; + + appendTest(details.name, details.testId, details.module); + + running = id("qunit-testresult-display"); + + if (running) { + addClass(running, "running"); + + bad = QUnit.config.reorder && details.previousFailure; + + running.innerHTML = [bad ? "Rerunning previously failed test:
                  " : "Running:
                  ", getNameHtml(details.name, details.module)].join(""); + } + }); + + function stripHtml(string) { + + // Strip tags, html entity and whitespaces + return string.replace(/<\/?[^>]+(>|$)/g, "").replace(/"/g, "").replace(/\s+/g, ""); + } + + QUnit.log(function (details) { + var assertList, + assertLi, + message, + expected, + actual, + diff, + showDiff = false, + testItem = id("qunit-test-output-" + details.testId); + + if (!testItem) { + return; + } + + message = escapeText(details.message) || (details.result ? "okay" : "failed"); + message = "" + message + ""; + message += "@ " + details.runtime + " ms"; + + // The pushFailure doesn't provide details.expected + // when it calls, it's implicit to also not show expected and diff stuff + // Also, we need to check details.expected existence, as it can exist and be undefined + if (!details.result && hasOwn.call(details, "expected")) { + if (details.negative) { + expected = "NOT " + QUnit.dump.parse(details.expected); + } else { + expected = QUnit.dump.parse(details.expected); + } + + actual = QUnit.dump.parse(details.actual); + message += ""; + + if (actual !== expected) { + + message += ""; + + if (typeof details.actual === "number" && typeof details.expected === "number") { + if (!isNaN(details.actual) && !isNaN(details.expected)) { + showDiff = true; + diff = details.actual - details.expected; + diff = (diff > 0 ? "+" : "") + diff; + } + } else if (typeof details.actual !== "boolean" && typeof details.expected !== "boolean") { + diff = QUnit.diff(expected, actual); + + // don't show diff if there is zero overlap + showDiff = stripHtml(diff).length !== stripHtml(expected).length + stripHtml(actual).length; + } + + if (showDiff) { + message += ""; + } + } else if (expected.indexOf("[object Array]") !== -1 || expected.indexOf("[object Object]") !== -1) { + message += ""; + } else { + message += ""; + } + + if (details.source) { + message += ""; + } + + message += "
                  Expected:
                  " + escapeText(expected) + "
                  Result:
                  " + escapeText(actual) + "
                  Diff:
                  " + diff + "
                  Message: " + "Diff suppressed as the depth of object is more than current max depth (" + QUnit.config.maxDepth + ").

                  Hint: Use QUnit.dump.maxDepth to " + " run with a higher max depth or " + "Rerun without max depth.

                  Message: " + "Diff suppressed as the expected and actual results have an equivalent" + " serialization
                  Source:
                  " + escapeText(details.source) + "
                  "; + + // This occurs when pushFailure is set and we have an extracted stack trace + } else if (!details.result && details.source) { + message += "" + "" + "
                  Source:
                  " + escapeText(details.source) + "
                  "; + } + + assertList = testItem.getElementsByTagName("ol")[0]; + + assertLi = document.createElement("li"); + assertLi.className = details.result ? "pass" : "fail"; + assertLi.innerHTML = message; + assertList.appendChild(assertLi); + }); + + QUnit.testDone(function (details) { + var testTitle, + time, + testItem, + assertList, + status, + good, + bad, + testCounts, + skipped, + sourceName, + tests = id("qunit-tests"); + + if (!tests) { + return; + } + + testItem = id("qunit-test-output-" + details.testId); + + removeClass(testItem, "running"); + + if (details.failed > 0) { + status = "failed"; + } else if (details.todo) { + status = "todo"; + } else { + status = details.skipped ? "skipped" : "passed"; + } + + assertList = testItem.getElementsByTagName("ol")[0]; + + good = details.passed; + bad = details.failed; + + // This test passed if it has no unexpected failed assertions + var testPassed = details.failed > 0 ? details.todo : !details.todo; + + if (testPassed) { + + // Collapse the passing tests + addClass(assertList, "qunit-collapsed"); + } else if (config.collapse) { + if (!collapseNext) { + + // Skip collapsing the first failing test + collapseNext = true; + } else { + + // Collapse remaining tests + addClass(assertList, "qunit-collapsed"); + } + } + + // The testItem.firstChild is the test name + testTitle = testItem.firstChild; + + testCounts = bad ? "" + bad + ", " + "" + good + ", " : ""; + + testTitle.innerHTML += " (" + testCounts + details.assertions.length + ")"; + + if (details.skipped) { + stats.skippedTests++; + + testItem.className = "skipped"; + skipped = document.createElement("em"); + skipped.className = "qunit-skipped-label"; + skipped.innerHTML = "skipped"; + testItem.insertBefore(skipped, testTitle); + } else { + addEvent(testTitle, "click", function () { + toggleClass(assertList, "qunit-collapsed"); + }); + + testItem.className = testPassed ? "pass" : "fail"; + + if (details.todo) { + var todoLabel = document.createElement("em"); + todoLabel.className = "qunit-todo-label"; + todoLabel.innerHTML = "todo"; + testItem.className += " todo"; + testItem.insertBefore(todoLabel, testTitle); + } + + time = document.createElement("span"); + time.className = "runtime"; + time.innerHTML = details.runtime + " ms"; + testItem.insertBefore(time, assertList); + + if (!testPassed) { + stats.failedTests++; + } else if (details.todo) { + stats.todoTests++; + } else { + stats.passedTests++; + } + } + + // Show the source of the test when showing assertions + if (details.source) { + sourceName = document.createElement("p"); + sourceName.innerHTML = "Source: " + escapeText(details.source); + addClass(sourceName, "qunit-source"); + if (testPassed) { + addClass(sourceName, "qunit-collapsed"); + } + addEvent(testTitle, "click", function () { + toggleClass(sourceName, "qunit-collapsed"); + }); + testItem.appendChild(sourceName); + } + + if (config.hidepassed && status === "passed") { + + // use removeChild instead of remove because of support + hiddenTests.push(testItem); + + tests.removeChild(testItem); + } + }); + + // Avoid readyState issue with phantomjs + // Ref: #818 + var notPhantom = function (p) { + return !(p && p.version && p.version.major > 0); + }(window$1.phantom); + + if (notPhantom && document.readyState === "complete") { + QUnit.load(); + } else { + addEvent(window$1, "load", QUnit.load); + } + + // Wrap window.onerror. We will call the original window.onerror to see if + // the existing handler fully handles the error; if not, we will call the + // QUnit.onError function. + var originalWindowOnError = window$1.onerror; + + // Cover uncaught exceptions + // Returning true will suppress the default browser handler, + // returning false will let it run. + window$1.onerror = function (message, fileName, lineNumber, columnNumber, errorObj) { + var ret = false; + if (originalWindowOnError) { + for (var _len = arguments.length, args = Array(_len > 5 ? _len - 5 : 0), _key = 5; _key < _len; _key++) { + args[_key - 5] = arguments[_key]; + } + + ret = originalWindowOnError.call.apply(originalWindowOnError, [this, message, fileName, lineNumber, columnNumber, errorObj].concat(args)); + } + + // Treat return value as window.onerror itself does, + // Only do our handling if not suppressed. + if (ret !== true) { + var error = { + message: message, + fileName: fileName, + lineNumber: lineNumber + }; + + // According to + // https://blog.sentry.io/2016/01/04/client-javascript-reporting-window-onerror, + // most modern browsers support an errorObj argument; use that to + // get a full stack trace if it's available. + if (errorObj && errorObj.stack) { + error.stacktrace = extractStacktrace(errorObj, 0); + } + + ret = QUnit.onError(error); + } + + return ret; + }; + + // Listen for unhandled rejections, and call QUnit.onUnhandledRejection + window$1.addEventListener("unhandledrejection", function (event) { + QUnit.onUnhandledRejection(event.reason); + }); + })(); + + /* + * This file is a modified version of google-diff-match-patch's JavaScript implementation + * (https://code.google.com/p/google-diff-match-patch/source/browse/trunk/javascript/diff_match_patch_uncompressed.js), + * modifications are licensed as more fully set forth in LICENSE.txt. + * + * The original source of google-diff-match-patch is attributable and licensed as follows: + * + * Copyright 2006 Google Inc. + * https://code.google.com/p/google-diff-match-patch/ + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * More Info: + * https://code.google.com/p/google-diff-match-patch/ + * + * Usage: QUnit.diff(expected, actual) + * + */ + QUnit.diff = function () { + function DiffMatchPatch() {} + + // DIFF FUNCTIONS + + /** + * The data structure representing a diff is an array of tuples: + * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] + * which means: delete 'Hello', add 'Goodbye' and keep ' world.' + */ + var DIFF_DELETE = -1, + DIFF_INSERT = 1, + DIFF_EQUAL = 0; + + /** + * Find the differences between two texts. Simplifies the problem by stripping + * any common prefix or suffix off the texts before diffing. + * @param {string} text1 Old string to be diffed. + * @param {string} text2 New string to be diffed. + * @param {boolean=} optChecklines Optional speedup flag. If present and false, + * then don't run a line-level diff first to identify the changed areas. + * Defaults to true, which does a faster, slightly less optimal diff. + * @return {!Array.} Array of diff tuples. + */ + DiffMatchPatch.prototype.DiffMain = function (text1, text2, optChecklines) { + var deadline, checklines, commonlength, commonprefix, commonsuffix, diffs; + + // The diff must be complete in up to 1 second. + deadline = new Date().getTime() + 1000; + + // Check for null inputs. + if (text1 === null || text2 === null) { + throw new Error("Null input. (DiffMain)"); + } + + // Check for equality (speedup). + if (text1 === text2) { + if (text1) { + return [[DIFF_EQUAL, text1]]; + } + return []; + } + + if (typeof optChecklines === "undefined") { + optChecklines = true; + } + + checklines = optChecklines; + + // Trim off common prefix (speedup). + commonlength = this.diffCommonPrefix(text1, text2); + commonprefix = text1.substring(0, commonlength); + text1 = text1.substring(commonlength); + text2 = text2.substring(commonlength); + + // Trim off common suffix (speedup). + commonlength = this.diffCommonSuffix(text1, text2); + commonsuffix = text1.substring(text1.length - commonlength); + text1 = text1.substring(0, text1.length - commonlength); + text2 = text2.substring(0, text2.length - commonlength); + + // Compute the diff on the middle block. + diffs = this.diffCompute(text1, text2, checklines, deadline); + + // Restore the prefix and suffix. + if (commonprefix) { + diffs.unshift([DIFF_EQUAL, commonprefix]); + } + if (commonsuffix) { + diffs.push([DIFF_EQUAL, commonsuffix]); + } + this.diffCleanupMerge(diffs); + return diffs; + }; + + /** + * Reduce the number of edits by eliminating operationally trivial equalities. + * @param {!Array.} diffs Array of diff tuples. + */ + DiffMatchPatch.prototype.diffCleanupEfficiency = function (diffs) { + var changes, equalities, equalitiesLength, lastequality, pointer, preIns, preDel, postIns, postDel; + changes = false; + equalities = []; // Stack of indices where equalities are found. + equalitiesLength = 0; // Keeping our own length var is faster in JS. + /** @type {?string} */ + lastequality = null; + + // Always equal to diffs[equalities[equalitiesLength - 1]][1] + pointer = 0; // Index of current position. + + // Is there an insertion operation before the last equality. + preIns = false; + + // Is there a deletion operation before the last equality. + preDel = false; + + // Is there an insertion operation after the last equality. + postIns = false; + + // Is there a deletion operation after the last equality. + postDel = false; + while (pointer < diffs.length) { + + // Equality found. + if (diffs[pointer][0] === DIFF_EQUAL) { + if (diffs[pointer][1].length < 4 && (postIns || postDel)) { + + // Candidate found. + equalities[equalitiesLength++] = pointer; + preIns = postIns; + preDel = postDel; + lastequality = diffs[pointer][1]; + } else { + + // Not a candidate, and can never become one. + equalitiesLength = 0; + lastequality = null; + } + postIns = postDel = false; + + // An insertion or deletion. + } else { + + if (diffs[pointer][0] === DIFF_DELETE) { + postDel = true; + } else { + postIns = true; + } + + /* + * Five types to be split: + * ABXYCD + * AXCD + * ABXC + * AXCD + * ABXC + */ + if (lastequality && (preIns && preDel && postIns && postDel || lastequality.length < 2 && preIns + preDel + postIns + postDel === 3)) { + + // Duplicate record. + diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastequality]); + + // Change second copy to insert. + diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; + equalitiesLength--; // Throw away the equality we just deleted; + lastequality = null; + if (preIns && preDel) { + + // No changes made which could affect previous entry, keep going. + postIns = postDel = true; + equalitiesLength = 0; + } else { + equalitiesLength--; // Throw away the previous equality. + pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; + postIns = postDel = false; + } + changes = true; + } + } + pointer++; + } + + if (changes) { + this.diffCleanupMerge(diffs); + } + }; + + /** + * Convert a diff array into a pretty HTML report. + * @param {!Array.} diffs Array of diff tuples. + * @param {integer} string to be beautified. + * @return {string} HTML representation. + */ + DiffMatchPatch.prototype.diffPrettyHtml = function (diffs) { + var op, + data, + x, + html = []; + for (x = 0; x < diffs.length; x++) { + op = diffs[x][0]; // Operation (insert, delete, equal) + data = diffs[x][1]; // Text of change. + switch (op) { + case DIFF_INSERT: + html[x] = "" + escapeText(data) + ""; + break; + case DIFF_DELETE: + html[x] = "" + escapeText(data) + ""; + break; + case DIFF_EQUAL: + html[x] = "" + escapeText(data) + ""; + break; + } + } + return html.join(""); + }; + + /** + * Determine the common prefix of two strings. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {number} The number of characters common to the start of each + * string. + */ + DiffMatchPatch.prototype.diffCommonPrefix = function (text1, text2) { + var pointermid, pointermax, pointermin, pointerstart; + + // Quick check for common null cases. + if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) { + return 0; + } + + // Binary search. + // Performance analysis: https://neil.fraser.name/news/2007/10/09/ + pointermin = 0; + pointermax = Math.min(text1.length, text2.length); + pointermid = pointermax; + pointerstart = 0; + while (pointermin < pointermid) { + if (text1.substring(pointerstart, pointermid) === text2.substring(pointerstart, pointermid)) { + pointermin = pointermid; + pointerstart = pointermin; + } else { + pointermax = pointermid; + } + pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); + } + return pointermid; + }; + + /** + * Determine the common suffix of two strings. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {number} The number of characters common to the end of each string. + */ + DiffMatchPatch.prototype.diffCommonSuffix = function (text1, text2) { + var pointermid, pointermax, pointermin, pointerend; + + // Quick check for common null cases. + if (!text1 || !text2 || text1.charAt(text1.length - 1) !== text2.charAt(text2.length - 1)) { + return 0; + } + + // Binary search. + // Performance analysis: https://neil.fraser.name/news/2007/10/09/ + pointermin = 0; + pointermax = Math.min(text1.length, text2.length); + pointermid = pointermax; + pointerend = 0; + while (pointermin < pointermid) { + if (text1.substring(text1.length - pointermid, text1.length - pointerend) === text2.substring(text2.length - pointermid, text2.length - pointerend)) { + pointermin = pointermid; + pointerend = pointermin; + } else { + pointermax = pointermid; + } + pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); + } + return pointermid; + }; + + /** + * Find the differences between two texts. Assumes that the texts do not + * have any common prefix or suffix. + * @param {string} text1 Old string to be diffed. + * @param {string} text2 New string to be diffed. + * @param {boolean} checklines Speedup flag. If false, then don't run a + * line-level diff first to identify the changed areas. + * If true, then run a faster, slightly less optimal diff. + * @param {number} deadline Time when the diff should be complete by. + * @return {!Array.} Array of diff tuples. + * @private + */ + DiffMatchPatch.prototype.diffCompute = function (text1, text2, checklines, deadline) { + var diffs, longtext, shorttext, i, hm, text1A, text2A, text1B, text2B, midCommon, diffsA, diffsB; + + if (!text1) { + + // Just add some text (speedup). + return [[DIFF_INSERT, text2]]; + } + + if (!text2) { + + // Just delete some text (speedup). + return [[DIFF_DELETE, text1]]; + } + + longtext = text1.length > text2.length ? text1 : text2; + shorttext = text1.length > text2.length ? text2 : text1; + i = longtext.indexOf(shorttext); + if (i !== -1) { + + // Shorter text is inside the longer text (speedup). + diffs = [[DIFF_INSERT, longtext.substring(0, i)], [DIFF_EQUAL, shorttext], [DIFF_INSERT, longtext.substring(i + shorttext.length)]]; + + // Swap insertions for deletions if diff is reversed. + if (text1.length > text2.length) { + diffs[0][0] = diffs[2][0] = DIFF_DELETE; + } + return diffs; + } + + if (shorttext.length === 1) { + + // Single character string. + // After the previous speedup, the character can't be an equality. + return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]]; + } + + // Check to see if the problem can be split in two. + hm = this.diffHalfMatch(text1, text2); + if (hm) { + + // A half-match was found, sort out the return data. + text1A = hm[0]; + text1B = hm[1]; + text2A = hm[2]; + text2B = hm[3]; + midCommon = hm[4]; + + // Send both pairs off for separate processing. + diffsA = this.DiffMain(text1A, text2A, checklines, deadline); + diffsB = this.DiffMain(text1B, text2B, checklines, deadline); + + // Merge the results. + return diffsA.concat([[DIFF_EQUAL, midCommon]], diffsB); + } + + if (checklines && text1.length > 100 && text2.length > 100) { + return this.diffLineMode(text1, text2, deadline); + } + + return this.diffBisect(text1, text2, deadline); + }; + + /** + * Do the two texts share a substring which is at least half the length of the + * longer text? + * This speedup can produce non-minimal diffs. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {Array.} Five element Array, containing the prefix of + * text1, the suffix of text1, the prefix of text2, the suffix of + * text2 and the common middle. Or null if there was no match. + * @private + */ + DiffMatchPatch.prototype.diffHalfMatch = function (text1, text2) { + var longtext, shorttext, dmp, text1A, text2B, text2A, text1B, midCommon, hm1, hm2, hm; + + longtext = text1.length > text2.length ? text1 : text2; + shorttext = text1.length > text2.length ? text2 : text1; + if (longtext.length < 4 || shorttext.length * 2 < longtext.length) { + return null; // Pointless. + } + dmp = this; // 'this' becomes 'window' in a closure. + + /** + * Does a substring of shorttext exist within longtext such that the substring + * is at least half the length of longtext? + * Closure, but does not reference any external variables. + * @param {string} longtext Longer string. + * @param {string} shorttext Shorter string. + * @param {number} i Start index of quarter length substring within longtext. + * @return {Array.} Five element Array, containing the prefix of + * longtext, the suffix of longtext, the prefix of shorttext, the suffix + * of shorttext and the common middle. Or null if there was no match. + * @private + */ + function diffHalfMatchI(longtext, shorttext, i) { + var seed, j, bestCommon, prefixLength, suffixLength, bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB; + + // Start with a 1/4 length substring at position i as a seed. + seed = longtext.substring(i, i + Math.floor(longtext.length / 4)); + j = -1; + bestCommon = ""; + while ((j = shorttext.indexOf(seed, j + 1)) !== -1) { + prefixLength = dmp.diffCommonPrefix(longtext.substring(i), shorttext.substring(j)); + suffixLength = dmp.diffCommonSuffix(longtext.substring(0, i), shorttext.substring(0, j)); + if (bestCommon.length < suffixLength + prefixLength) { + bestCommon = shorttext.substring(j - suffixLength, j) + shorttext.substring(j, j + prefixLength); + bestLongtextA = longtext.substring(0, i - suffixLength); + bestLongtextB = longtext.substring(i + prefixLength); + bestShorttextA = shorttext.substring(0, j - suffixLength); + bestShorttextB = shorttext.substring(j + prefixLength); + } + } + if (bestCommon.length * 2 >= longtext.length) { + return [bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB, bestCommon]; + } else { + return null; + } + } + + // First check if the second quarter is the seed for a half-match. + hm1 = diffHalfMatchI(longtext, shorttext, Math.ceil(longtext.length / 4)); + + // Check again based on the third quarter. + hm2 = diffHalfMatchI(longtext, shorttext, Math.ceil(longtext.length / 2)); + if (!hm1 && !hm2) { + return null; + } else if (!hm2) { + hm = hm1; + } else if (!hm1) { + hm = hm2; + } else { + + // Both matched. Select the longest. + hm = hm1[4].length > hm2[4].length ? hm1 : hm2; + } + + // A half-match was found, sort out the return data. + if (text1.length > text2.length) { + text1A = hm[0]; + text1B = hm[1]; + text2A = hm[2]; + text2B = hm[3]; + } else { + text2A = hm[0]; + text2B = hm[1]; + text1A = hm[2]; + text1B = hm[3]; + } + midCommon = hm[4]; + return [text1A, text1B, text2A, text2B, midCommon]; + }; + + /** + * Do a quick line-level diff on both strings, then rediff the parts for + * greater accuracy. + * This speedup can produce non-minimal diffs. + * @param {string} text1 Old string to be diffed. + * @param {string} text2 New string to be diffed. + * @param {number} deadline Time when the diff should be complete by. + * @return {!Array.} Array of diff tuples. + * @private + */ + DiffMatchPatch.prototype.diffLineMode = function (text1, text2, deadline) { + var a, diffs, linearray, pointer, countInsert, countDelete, textInsert, textDelete, j; + + // Scan the text on a line-by-line basis first. + a = this.diffLinesToChars(text1, text2); + text1 = a.chars1; + text2 = a.chars2; + linearray = a.lineArray; + + diffs = this.DiffMain(text1, text2, false, deadline); + + // Convert the diff back to original text. + this.diffCharsToLines(diffs, linearray); + + // Eliminate freak matches (e.g. blank lines) + this.diffCleanupSemantic(diffs); + + // Rediff any replacement blocks, this time character-by-character. + // Add a dummy entry at the end. + diffs.push([DIFF_EQUAL, ""]); + pointer = 0; + countDelete = 0; + countInsert = 0; + textDelete = ""; + textInsert = ""; + while (pointer < diffs.length) { + switch (diffs[pointer][0]) { + case DIFF_INSERT: + countInsert++; + textInsert += diffs[pointer][1]; + break; + case DIFF_DELETE: + countDelete++; + textDelete += diffs[pointer][1]; + break; + case DIFF_EQUAL: + + // Upon reaching an equality, check for prior redundancies. + if (countDelete >= 1 && countInsert >= 1) { + + // Delete the offending records and add the merged ones. + diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert); + pointer = pointer - countDelete - countInsert; + a = this.DiffMain(textDelete, textInsert, false, deadline); + for (j = a.length - 1; j >= 0; j--) { + diffs.splice(pointer, 0, a[j]); + } + pointer = pointer + a.length; + } + countInsert = 0; + countDelete = 0; + textDelete = ""; + textInsert = ""; + break; + } + pointer++; + } + diffs.pop(); // Remove the dummy entry at the end. + + return diffs; + }; + + /** + * Find the 'middle snake' of a diff, split the problem in two + * and return the recursively constructed diff. + * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations. + * @param {string} text1 Old string to be diffed. + * @param {string} text2 New string to be diffed. + * @param {number} deadline Time at which to bail if not yet complete. + * @return {!Array.} Array of diff tuples. + * @private + */ + DiffMatchPatch.prototype.diffBisect = function (text1, text2, deadline) { + var text1Length, text2Length, maxD, vOffset, vLength, v1, v2, x, delta, front, k1start, k1end, k2start, k2end, k2Offset, k1Offset, x1, x2, y1, y2, d, k1, k2; + + // Cache the text lengths to prevent multiple calls. + text1Length = text1.length; + text2Length = text2.length; + maxD = Math.ceil((text1Length + text2Length) / 2); + vOffset = maxD; + vLength = 2 * maxD; + v1 = new Array(vLength); + v2 = new Array(vLength); + + // Setting all elements to -1 is faster in Chrome & Firefox than mixing + // integers and undefined. + for (x = 0; x < vLength; x++) { + v1[x] = -1; + v2[x] = -1; + } + v1[vOffset + 1] = 0; + v2[vOffset + 1] = 0; + delta = text1Length - text2Length; + + // If the total number of characters is odd, then the front path will collide + // with the reverse path. + front = delta % 2 !== 0; + + // Offsets for start and end of k loop. + // Prevents mapping of space beyond the grid. + k1start = 0; + k1end = 0; + k2start = 0; + k2end = 0; + for (d = 0; d < maxD; d++) { + + // Bail out if deadline is reached. + if (new Date().getTime() > deadline) { + break; + } + + // Walk the front path one step. + for (k1 = -d + k1start; k1 <= d - k1end; k1 += 2) { + k1Offset = vOffset + k1; + if (k1 === -d || k1 !== d && v1[k1Offset - 1] < v1[k1Offset + 1]) { + x1 = v1[k1Offset + 1]; + } else { + x1 = v1[k1Offset - 1] + 1; + } + y1 = x1 - k1; + while (x1 < text1Length && y1 < text2Length && text1.charAt(x1) === text2.charAt(y1)) { + x1++; + y1++; + } + v1[k1Offset] = x1; + if (x1 > text1Length) { + + // Ran off the right of the graph. + k1end += 2; + } else if (y1 > text2Length) { + + // Ran off the bottom of the graph. + k1start += 2; + } else if (front) { + k2Offset = vOffset + delta - k1; + if (k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] !== -1) { + + // Mirror x2 onto top-left coordinate system. + x2 = text1Length - v2[k2Offset]; + if (x1 >= x2) { + + // Overlap detected. + return this.diffBisectSplit(text1, text2, x1, y1, deadline); + } + } + } + } + + // Walk the reverse path one step. + for (k2 = -d + k2start; k2 <= d - k2end; k2 += 2) { + k2Offset = vOffset + k2; + if (k2 === -d || k2 !== d && v2[k2Offset - 1] < v2[k2Offset + 1]) { + x2 = v2[k2Offset + 1]; + } else { + x2 = v2[k2Offset - 1] + 1; + } + y2 = x2 - k2; + while (x2 < text1Length && y2 < text2Length && text1.charAt(text1Length - x2 - 1) === text2.charAt(text2Length - y2 - 1)) { + x2++; + y2++; + } + v2[k2Offset] = x2; + if (x2 > text1Length) { + + // Ran off the left of the graph. + k2end += 2; + } else if (y2 > text2Length) { + + // Ran off the top of the graph. + k2start += 2; + } else if (!front) { + k1Offset = vOffset + delta - k2; + if (k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] !== -1) { + x1 = v1[k1Offset]; + y1 = vOffset + x1 - k1Offset; + + // Mirror x2 onto top-left coordinate system. + x2 = text1Length - x2; + if (x1 >= x2) { + + // Overlap detected. + return this.diffBisectSplit(text1, text2, x1, y1, deadline); + } + } + } + } + } + + // Diff took too long and hit the deadline or + // number of diffs equals number of characters, no commonality at all. + return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]]; + }; + + /** + * Given the location of the 'middle snake', split the diff in two parts + * and recurse. + * @param {string} text1 Old string to be diffed. + * @param {string} text2 New string to be diffed. + * @param {number} x Index of split point in text1. + * @param {number} y Index of split point in text2. + * @param {number} deadline Time at which to bail if not yet complete. + * @return {!Array.} Array of diff tuples. + * @private + */ + DiffMatchPatch.prototype.diffBisectSplit = function (text1, text2, x, y, deadline) { + var text1a, text1b, text2a, text2b, diffs, diffsb; + text1a = text1.substring(0, x); + text2a = text2.substring(0, y); + text1b = text1.substring(x); + text2b = text2.substring(y); + + // Compute both diffs serially. + diffs = this.DiffMain(text1a, text2a, false, deadline); + diffsb = this.DiffMain(text1b, text2b, false, deadline); + + return diffs.concat(diffsb); + }; + + /** + * Reduce the number of edits by eliminating semantically trivial equalities. + * @param {!Array.} diffs Array of diff tuples. + */ + DiffMatchPatch.prototype.diffCleanupSemantic = function (diffs) { + var changes, equalities, equalitiesLength, lastequality, pointer, lengthInsertions2, lengthDeletions2, lengthInsertions1, lengthDeletions1, deletion, insertion, overlapLength1, overlapLength2; + changes = false; + equalities = []; // Stack of indices where equalities are found. + equalitiesLength = 0; // Keeping our own length var is faster in JS. + /** @type {?string} */ + lastequality = null; + + // Always equal to diffs[equalities[equalitiesLength - 1]][1] + pointer = 0; // Index of current position. + + // Number of characters that changed prior to the equality. + lengthInsertions1 = 0; + lengthDeletions1 = 0; + + // Number of characters that changed after the equality. + lengthInsertions2 = 0; + lengthDeletions2 = 0; + while (pointer < diffs.length) { + if (diffs[pointer][0] === DIFF_EQUAL) { + // Equality found. + equalities[equalitiesLength++] = pointer; + lengthInsertions1 = lengthInsertions2; + lengthDeletions1 = lengthDeletions2; + lengthInsertions2 = 0; + lengthDeletions2 = 0; + lastequality = diffs[pointer][1]; + } else { + // An insertion or deletion. + if (diffs[pointer][0] === DIFF_INSERT) { + lengthInsertions2 += diffs[pointer][1].length; + } else { + lengthDeletions2 += diffs[pointer][1].length; + } + + // Eliminate an equality that is smaller or equal to the edits on both + // sides of it. + if (lastequality && lastequality.length <= Math.max(lengthInsertions1, lengthDeletions1) && lastequality.length <= Math.max(lengthInsertions2, lengthDeletions2)) { + + // Duplicate record. + diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastequality]); + + // Change second copy to insert. + diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; + + // Throw away the equality we just deleted. + equalitiesLength--; + + // Throw away the previous equality (it needs to be reevaluated). + equalitiesLength--; + pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; + + // Reset the counters. + lengthInsertions1 = 0; + lengthDeletions1 = 0; + lengthInsertions2 = 0; + lengthDeletions2 = 0; + lastequality = null; + changes = true; + } + } + pointer++; + } + + // Normalize the diff. + if (changes) { + this.diffCleanupMerge(diffs); + } + + // Find any overlaps between deletions and insertions. + // e.g: abcxxxxxxdef + // -> abcxxxdef + // e.g: xxxabcdefxxx + // -> defxxxabc + // Only extract an overlap if it is as big as the edit ahead or behind it. + pointer = 1; + while (pointer < diffs.length) { + if (diffs[pointer - 1][0] === DIFF_DELETE && diffs[pointer][0] === DIFF_INSERT) { + deletion = diffs[pointer - 1][1]; + insertion = diffs[pointer][1]; + overlapLength1 = this.diffCommonOverlap(deletion, insertion); + overlapLength2 = this.diffCommonOverlap(insertion, deletion); + if (overlapLength1 >= overlapLength2) { + if (overlapLength1 >= deletion.length / 2 || overlapLength1 >= insertion.length / 2) { + + // Overlap found. Insert an equality and trim the surrounding edits. + diffs.splice(pointer, 0, [DIFF_EQUAL, insertion.substring(0, overlapLength1)]); + diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlapLength1); + diffs[pointer + 1][1] = insertion.substring(overlapLength1); + pointer++; + } + } else { + if (overlapLength2 >= deletion.length / 2 || overlapLength2 >= insertion.length / 2) { + + // Reverse overlap found. + // Insert an equality and swap and trim the surrounding edits. + diffs.splice(pointer, 0, [DIFF_EQUAL, deletion.substring(0, overlapLength2)]); + + diffs[pointer - 1][0] = DIFF_INSERT; + diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlapLength2); + diffs[pointer + 1][0] = DIFF_DELETE; + diffs[pointer + 1][1] = deletion.substring(overlapLength2); + pointer++; + } + } + pointer++; + } + pointer++; + } + }; + + /** + * Determine if the suffix of one string is the prefix of another. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {number} The number of characters common to the end of the first + * string and the start of the second string. + * @private + */ + DiffMatchPatch.prototype.diffCommonOverlap = function (text1, text2) { + var text1Length, text2Length, textLength, best, length, pattern, found; + + // Cache the text lengths to prevent multiple calls. + text1Length = text1.length; + text2Length = text2.length; + + // Eliminate the null case. + if (text1Length === 0 || text2Length === 0) { + return 0; + } + + // Truncate the longer string. + if (text1Length > text2Length) { + text1 = text1.substring(text1Length - text2Length); + } else if (text1Length < text2Length) { + text2 = text2.substring(0, text1Length); + } + textLength = Math.min(text1Length, text2Length); + + // Quick check for the worst case. + if (text1 === text2) { + return textLength; + } + + // Start by looking for a single character match + // and increase length until no match is found. + // Performance analysis: https://neil.fraser.name/news/2010/11/04/ + best = 0; + length = 1; + while (true) { + pattern = text1.substring(textLength - length); + found = text2.indexOf(pattern); + if (found === -1) { + return best; + } + length += found; + if (found === 0 || text1.substring(textLength - length) === text2.substring(0, length)) { + best = length; + length++; + } + } + }; + + /** + * Split two texts into an array of strings. Reduce the texts to a string of + * hashes where each Unicode character represents one line. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {{chars1: string, chars2: string, lineArray: !Array.}} + * An object containing the encoded text1, the encoded text2 and + * the array of unique strings. + * The zeroth element of the array of unique strings is intentionally blank. + * @private + */ + DiffMatchPatch.prototype.diffLinesToChars = function (text1, text2) { + var lineArray, lineHash, chars1, chars2; + lineArray = []; // E.g. lineArray[4] === 'Hello\n' + lineHash = {}; // E.g. lineHash['Hello\n'] === 4 + + // '\x00' is a valid character, but various debuggers don't like it. + // So we'll insert a junk entry to avoid generating a null character. + lineArray[0] = ""; + + /** + * Split a text into an array of strings. Reduce the texts to a string of + * hashes where each Unicode character represents one line. + * Modifies linearray and linehash through being a closure. + * @param {string} text String to encode. + * @return {string} Encoded string. + * @private + */ + function diffLinesToCharsMunge(text) { + var chars, lineStart, lineEnd, lineArrayLength, line; + chars = ""; + + // Walk the text, pulling out a substring for each line. + // text.split('\n') would would temporarily double our memory footprint. + // Modifying text would create many large strings to garbage collect. + lineStart = 0; + lineEnd = -1; + + // Keeping our own length variable is faster than looking it up. + lineArrayLength = lineArray.length; + while (lineEnd < text.length - 1) { + lineEnd = text.indexOf("\n", lineStart); + if (lineEnd === -1) { + lineEnd = text.length - 1; + } + line = text.substring(lineStart, lineEnd + 1); + lineStart = lineEnd + 1; + + var lineHashExists = lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : lineHash[line] !== undefined; + + if (lineHashExists) { + chars += String.fromCharCode(lineHash[line]); + } else { + chars += String.fromCharCode(lineArrayLength); + lineHash[line] = lineArrayLength; + lineArray[lineArrayLength++] = line; + } + } + return chars; + } + + chars1 = diffLinesToCharsMunge(text1); + chars2 = diffLinesToCharsMunge(text2); + return { + chars1: chars1, + chars2: chars2, + lineArray: lineArray + }; + }; + + /** + * Rehydrate the text in a diff from a string of line hashes to real lines of + * text. + * @param {!Array.} diffs Array of diff tuples. + * @param {!Array.} lineArray Array of unique strings. + * @private + */ + DiffMatchPatch.prototype.diffCharsToLines = function (diffs, lineArray) { + var x, chars, text, y; + for (x = 0; x < diffs.length; x++) { + chars = diffs[x][1]; + text = []; + for (y = 0; y < chars.length; y++) { + text[y] = lineArray[chars.charCodeAt(y)]; + } + diffs[x][1] = text.join(""); + } + }; + + /** + * Reorder and merge like edit sections. Merge equalities. + * Any edit section can move as long as it doesn't cross an equality. + * @param {!Array.} diffs Array of diff tuples. + */ + DiffMatchPatch.prototype.diffCleanupMerge = function (diffs) { + var pointer, countDelete, countInsert, textInsert, textDelete, commonlength, changes, diffPointer, position; + diffs.push([DIFF_EQUAL, ""]); // Add a dummy entry at the end. + pointer = 0; + countDelete = 0; + countInsert = 0; + textDelete = ""; + textInsert = ""; + + while (pointer < diffs.length) { + switch (diffs[pointer][0]) { + case DIFF_INSERT: + countInsert++; + textInsert += diffs[pointer][1]; + pointer++; + break; + case DIFF_DELETE: + countDelete++; + textDelete += diffs[pointer][1]; + pointer++; + break; + case DIFF_EQUAL: + + // Upon reaching an equality, check for prior redundancies. + if (countDelete + countInsert > 1) { + if (countDelete !== 0 && countInsert !== 0) { + + // Factor out any common prefixes. + commonlength = this.diffCommonPrefix(textInsert, textDelete); + if (commonlength !== 0) { + if (pointer - countDelete - countInsert > 0 && diffs[pointer - countDelete - countInsert - 1][0] === DIFF_EQUAL) { + diffs[pointer - countDelete - countInsert - 1][1] += textInsert.substring(0, commonlength); + } else { + diffs.splice(0, 0, [DIFF_EQUAL, textInsert.substring(0, commonlength)]); + pointer++; + } + textInsert = textInsert.substring(commonlength); + textDelete = textDelete.substring(commonlength); + } + + // Factor out any common suffixies. + commonlength = this.diffCommonSuffix(textInsert, textDelete); + if (commonlength !== 0) { + diffs[pointer][1] = textInsert.substring(textInsert.length - commonlength) + diffs[pointer][1]; + textInsert = textInsert.substring(0, textInsert.length - commonlength); + textDelete = textDelete.substring(0, textDelete.length - commonlength); + } + } + + // Delete the offending records and add the merged ones. + if (countDelete === 0) { + diffs.splice(pointer - countInsert, countDelete + countInsert, [DIFF_INSERT, textInsert]); + } else if (countInsert === 0) { + diffs.splice(pointer - countDelete, countDelete + countInsert, [DIFF_DELETE, textDelete]); + } else { + diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert, [DIFF_DELETE, textDelete], [DIFF_INSERT, textInsert]); + } + pointer = pointer - countDelete - countInsert + (countDelete ? 1 : 0) + (countInsert ? 1 : 0) + 1; + } else if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) { + + // Merge this equality with the previous one. + diffs[pointer - 1][1] += diffs[pointer][1]; + diffs.splice(pointer, 1); + } else { + pointer++; + } + countInsert = 0; + countDelete = 0; + textDelete = ""; + textInsert = ""; + break; + } + } + if (diffs[diffs.length - 1][1] === "") { + diffs.pop(); // Remove the dummy entry at the end. + } + + // Second pass: look for single edits surrounded on both sides by equalities + // which can be shifted sideways to eliminate an equality. + // e.g: ABAC -> ABAC + changes = false; + pointer = 1; + + // Intentionally ignore the first and last element (don't need checking). + while (pointer < diffs.length - 1) { + if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) { + + diffPointer = diffs[pointer][1]; + position = diffPointer.substring(diffPointer.length - diffs[pointer - 1][1].length); + + // This is a single edit surrounded by equalities. + if (position === diffs[pointer - 1][1]) { + + // Shift the edit over the previous equality. + diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length); + diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; + diffs.splice(pointer - 1, 1); + changes = true; + } else if (diffPointer.substring(0, diffs[pointer + 1][1].length) === diffs[pointer + 1][1]) { + + // Shift the edit over the next equality. + diffs[pointer - 1][1] += diffs[pointer + 1][1]; + diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1]; + diffs.splice(pointer + 1, 1); + changes = true; + } + } + pointer++; + } + + // If shifts were made, the diff needs reordering and another shift sweep. + if (changes) { + this.diffCleanupMerge(diffs); + } + }; + + return function (o, n) { + var diff, output, text; + diff = new DiffMatchPatch(); + output = diff.DiffMain(o, n); + diff.diffCleanupEfficiency(output); + text = diff.diffPrettyHtml(output); + + return text; + }; + }(); + +}((function() { return this; }()))); diff --git a/test/locale-tests.js b/test/locale-tests.js index dd43ab6a..b70334f9 100644 --- a/test/locale-tests.js +++ b/test/locale-tests.js @@ -1,101 +1,101 @@ /*global QUnit:false*/ QUnit.module('Localization Tests', { - afterEach: function() { - ko.validation.locale('en-US'); - } + afterEach: function() { + ko.validation.locale('en-US'); + } }); QUnit.test('Default locale should be en-us', function(assert) { - assert.equal(ko.validation.locale(), 'en-us'); + assert.equal(ko.validation.locale(), 'en-us'); }); QUnit.test('Locale identifiers should be case insensitive', function(assert) { - assert.equal(ko.validation.locale('RO-RO'), 'ro-ro'); + assert.equal(ko.validation.locale('RO-RO'), 'ro-ro'); }); QUnit.test('Changing locale should change rules messages', function(assert) { - ko.validation.locale('ro-RO'); - assert.equal(ko.validation.rules.required.message, 'Acest câmp este obligatoriu.'); + ko.validation.locale('ro-RO'); + assert.equal(ko.validation.rules.required.message, 'Acest câmp este obligatoriu.'); }); QUnit.test('Reverting to default locale is possible', function(assert) { - ko.validation.locale('ro-RO'); - assert.equal(ko.validation.locale(), 'ro-ro'); - assert.equal(ko.validation.rules.required.message, 'Acest câmp este obligatoriu.'); + ko.validation.locale('ro-RO'); + assert.equal(ko.validation.locale(), 'ro-ro'); + assert.equal(ko.validation.rules.required.message, 'Acest câmp este obligatoriu.'); - ko.validation.locale('en-us'); - assert.equal(ko.validation.locale(), 'en-us'); - assert.equal(ko.validation.rules.required.message, 'This field is required.'); + ko.validation.locale('en-us'); + assert.equal(ko.validation.locale(), 'en-us'); + assert.equal(ko.validation.rules.required.message, 'This field is required.'); }); QUnit.test('Locale does not change when locale name is falsy', function(assert) { - var currentLocale = ko.validation.locale(); - assert.equal(currentLocale, 'en-us'); + var currentLocale = ko.validation.locale(); + assert.equal(currentLocale, 'en-us'); - ko.validation.locale(null); - assert.equal(currentLocale, 'en-us'); + ko.validation.locale(null); + assert.equal(currentLocale, 'en-us'); - ko.validation.locale(false); - assert.equal(currentLocale, 'en-us'); + ko.validation.locale(false); + assert.equal(currentLocale, 'en-us'); - ko.validation.locale(undefined); - assert.equal(currentLocale, 'en-us'); + ko.validation.locale(undefined); + assert.equal(currentLocale, 'en-us'); - ko.validation.locale(''); - assert.equal(currentLocale, 'en-us'); + ko.validation.locale(''); + assert.equal(currentLocale, 'en-us'); }); QUnit.test('Changing locale to a not loaded language throws', function(assert) { - assert.throws(function() { - ko.validation.locale('xyz'); - }); + assert.throws(function() { + ko.validation.locale('xyz'); + }); }); QUnit.test('Defining locales works', function(assert) { - var result = ko.validation.defineLocale('de-DE', { - required: 'Dieses Feld ist erforderlich.' - }); - assert.equal(ko.validation.locale('de-DE'), 'de-de'); - assert.equal(ko.validation.rules.required.message, 'Dieses Feld ist erforderlich.'); + var result = ko.validation.defineLocale('de-DE', { + required: 'Dieses Feld ist erforderlich.' + }); + assert.equal(ko.validation.locale('de-DE'), 'de-de'); + assert.equal(ko.validation.rules.required.message, 'Dieses Feld ist erforderlich.'); - // Since the localization specified only required rule, the others should be left to their original values - assert.equal(ko.validation.rules.email.message, 'Please enter a proper email address.'); + // Since the localization specified only required rule, the others should be left to their original values + assert.equal(ko.validation.rules.email.message, 'Please enter a proper email address.'); - // defineLocale should return the values that were passed in - assert.deepEqual(result, {required: 'Dieses Feld ist erforderlich.'}); + // defineLocale should return the values that were passed in + assert.deepEqual(result, {required: 'Dieses Feld ist erforderlich.'}); }); QUnit.test('Localization files can be loaded and applied', function(assert) { - // Simple check to ensure localization files can be loaded with script tag - assert.equal(ko.validation.locale('ar-JO'), 'ar-jo', 'Arabic - Jordan (ar-JO)'); - assert.equal(ko.validation.locale('bg-BG'), 'bg-bg', 'Bulgarian - Bulgaria (bg-BG)'); - assert.equal(ko.validation.locale('ca-ES'), 'ca-es', 'Catalan - Catalan (ca-ES)'); - assert.equal(ko.validation.locale('cs-CZ'), 'cs-cz', 'Czech - Czech Republic (cs-CZ)'); - assert.equal(ko.validation.locale('da-DK'), 'da-dk', 'Danish - Denmark (da-DK)'); - assert.equal(ko.validation.locale('de-DE'), 'de-de', 'German - Germany (de-DE)'); - assert.equal(ko.validation.locale('el-GR'), 'el-gr', 'Greek - Greece (el-GR)'); - assert.equal(ko.validation.locale('en-US'), 'en-us', 'English - United States (en-US)'); - assert.equal(ko.validation.locale('es-ES'), 'es-es', 'Spanish - Spain (es-ES)'); - assert.equal(ko.validation.locale('fa-IR'), 'fa-ir', 'Farsi - Iran (fa-IR)'); - assert.equal(ko.validation.locale('fr-FR'), 'fr-fr', 'French - France (fr-FR)'); - assert.equal(ko.validation.locale('he-IL'), 'he-il', 'Hebrew - Israel (he-IL)'); - assert.equal(ko.validation.locale('hr-HR'), 'hr-hr', 'Croatian - Croatia (hr-HR)'); - assert.equal(ko.validation.locale('hu-HU'), 'hu-hu', 'Hungarian - Hungary (hu-HU)'); - assert.equal(ko.validation.locale('it-IT'), 'it-it', 'Italian - Italy (it-IT)'); - assert.equal(ko.validation.locale('ja-JP'), 'ja-jp', 'Japanese - Japan (ja-JP)'); - assert.equal(ko.validation.locale('ko-KR'), 'ko-kr', 'Korean - Korea (ko-KR)'); - assert.equal(ko.validation.locale('lv-LV'), 'lv-lv', 'Latvian - Latvia (lv-LV)'); - assert.equal(ko.validation.locale('nb-NO'), 'nb-no', 'Norwegian (Bokmål) - Norway (nb-NO)'); - assert.equal(ko.validation.locale('nl-BE'), 'nl-be', 'Dutch - Belgium (nl-BE)'); - assert.equal(ko.validation.locale('nl-NL'), 'nl-nl', 'Dutch - The Netherlands (nl-NL)'); - assert.equal(ko.validation.locale('pl-PL'), 'pl-pl', 'Polish - Poland (pl-PL)'); - assert.equal(ko.validation.locale('pt-BR'), 'pt-br', 'Portuguese - Brazil (pt-BR)'); - assert.equal(ko.validation.locale('pt-PT'), 'pt-pt', 'Portuguese - Portugal (pt-PT)'); - assert.equal(ko.validation.locale('ro-RO'), 'ro-ro', 'Romanian - Romania (ro-RO)'); - assert.equal(ko.validation.locale('ru-RU'), 'ru-ru', 'Russian - Russia (ru-RU)'); - assert.equal(ko.validation.locale('sv-SE'), 'sv-se', 'Swedish - Sweden (sv-SE)'); - assert.equal(ko.validation.locale('tr-TR'), 'tr-tr', 'Turkish - Turkey (tr-TR)'); - assert.equal(ko.validation.locale('zh-CN'), 'zh-cn', 'Chinese - China (zh-CN)'); - assert.equal(ko.validation.locale('zh-TW'), 'zh-tw', 'Chinese - Taiwan (zh-TW)'); + // Simple check to ensure localization files can be loaded with script tag + assert.equal(ko.validation.locale('ar-JO'), 'ar-jo', 'Arabic - Jordan (ar-JO)'); + assert.equal(ko.validation.locale('bg-BG'), 'bg-bg', 'Bulgarian - Bulgaria (bg-BG)'); + assert.equal(ko.validation.locale('ca-ES'), 'ca-es', 'Catalan - Catalan (ca-ES)'); + assert.equal(ko.validation.locale('cs-CZ'), 'cs-cz', 'Czech - Czech Republic (cs-CZ)'); + assert.equal(ko.validation.locale('da-DK'), 'da-dk', 'Danish - Denmark (da-DK)'); + assert.equal(ko.validation.locale('de-DE'), 'de-de', 'German - Germany (de-DE)'); + assert.equal(ko.validation.locale('el-GR'), 'el-gr', 'Greek - Greece (el-GR)'); + assert.equal(ko.validation.locale('en-US'), 'en-us', 'English - United States (en-US)'); + assert.equal(ko.validation.locale('es-ES'), 'es-es', 'Spanish - Spain (es-ES)'); + assert.equal(ko.validation.locale('fa-IR'), 'fa-ir', 'Farsi - Iran (fa-IR)'); + assert.equal(ko.validation.locale('fr-FR'), 'fr-fr', 'French - France (fr-FR)'); + assert.equal(ko.validation.locale('he-IL'), 'he-il', 'Hebrew - Israel (he-IL)'); + assert.equal(ko.validation.locale('hr-HR'), 'hr-hr', 'Croatian - Croatia (hr-HR)'); + assert.equal(ko.validation.locale('hu-HU'), 'hu-hu', 'Hungarian - Hungary (hu-HU)'); + assert.equal(ko.validation.locale('it-IT'), 'it-it', 'Italian - Italy (it-IT)'); + assert.equal(ko.validation.locale('ja-JP'), 'ja-jp', 'Japanese - Japan (ja-JP)'); + assert.equal(ko.validation.locale('ko-KR'), 'ko-kr', 'Korean - Korea (ko-KR)'); + assert.equal(ko.validation.locale('lv-LV'), 'lv-lv', 'Latvian - Latvia (lv-LV)'); + assert.equal(ko.validation.locale('nb-NO'), 'nb-no', 'Norwegian (Bokmål) - Norway (nb-NO)'); + assert.equal(ko.validation.locale('nl-BE'), 'nl-be', 'Dutch - Belgium (nl-BE)'); + assert.equal(ko.validation.locale('nl-NL'), 'nl-nl', 'Dutch - The Netherlands (nl-NL)'); + assert.equal(ko.validation.locale('pl-PL'), 'pl-pl', 'Polish - Poland (pl-PL)'); + assert.equal(ko.validation.locale('pt-BR'), 'pt-br', 'Portuguese - Brazil (pt-BR)'); + assert.equal(ko.validation.locale('pt-PT'), 'pt-pt', 'Portuguese - Portugal (pt-PT)'); + assert.equal(ko.validation.locale('ro-RO'), 'ro-ro', 'Romanian - Romania (ro-RO)'); + assert.equal(ko.validation.locale('ru-RU'), 'ru-ru', 'Russian - Russia (ru-RU)'); + assert.equal(ko.validation.locale('sv-SE'), 'sv-se', 'Swedish - Sweden (sv-SE)'); + assert.equal(ko.validation.locale('tr-TR'), 'tr-tr', 'Turkish - Turkey (tr-TR)'); + assert.equal(ko.validation.locale('zh-CN'), 'zh-cn', 'Chinese - China (zh-CN)'); + assert.equal(ko.validation.locale('zh-TW'), 'zh-tw', 'Chinese - Taiwan (zh-TW)'); }); diff --git a/test/test-runner-2.3.0.html b/test/test-runner-2.3.0.html index d35ed0c8..c6f6346a 100644 --- a/test/test-runner-2.3.0.html +++ b/test/test-runner-2.3.0.html @@ -1,8 +1,8 @@  - - + + diff --git a/test/test-runner-3.4.2.html b/test/test-runner-3.4.2.html index a5461e62..946bb4f1 100644 --- a/test/test-runner-3.4.2.html +++ b/test/test-runner-3.4.2.html @@ -1,8 +1,8 @@  - - + + diff --git a/test/test-runner-3.5.0.html b/test/test-runner-3.5.0.html index bcc2ef57..96fa1fba 100644 --- a/test/test-runner-3.5.0.html +++ b/test/test-runner-3.5.0.html @@ -1,8 +1,8 @@  - - + + diff --git a/test/validation-ui-tests.js b/test/validation-ui-tests.js index 63d82f6d..34f91640 100644 --- a/test/validation-ui-tests.js +++ b/test/validation-ui-tests.js @@ -1,220 +1,219 @@ /*global QUnit:false, $:false*/ - QUnit.module('UI Tests', { - afterEach: function() { - var $element = $('#testContainer'); - ko.cleanNode($element[0]); - $element.empty(); - ko.validation.reset(); - } + afterEach: function() { + var $element = $('#testContainer'); + ko.cleanNode($element[0]); + $element.empty(); + ko.validation.reset(); + } }); //utility functions var applyTestBindings = function(vm) { - ko.applyBindingsWithValidation(vm, $('#testContainer')[0]); + ko.applyBindingsWithValidation(vm, $('#testContainer')[0]); }; var addTestHtml = function(html) { - $('#testContainer').html(html); + $('#testContainer').html(html); }; QUnit.test('hasAttribute works in old IE', function(assert) { - addTestHtml(''); + addTestHtml(''); - var el = $('#myTestInput')[0]; + var el = $('#myTestInput')[0]; - assert.ok(el, 'found element'); - assert.ok(ko.validation.utils.hasAttribute(el, 'required'), 'element correctly has html5 input attribute'); - assert.ok(!ko.validation.utils.hasAttribute(el, 'pattern'), 'element correctly does not have html5 input attribute'); + assert.ok(el, 'found element'); + assert.ok(ko.validation.utils.hasAttribute(el, 'required'), 'element correctly has html5 input attribute'); + assert.ok(!ko.validation.utils.hasAttribute(el, 'pattern'), 'element correctly does not have html5 input attribute'); }); QUnit.test('checked binding sets error class on radio buttons', function(assert) { - addTestHtml("" + - "" + - ""); + addTestHtml("" + + "" + + ""); - var $input = $('#testInput2'), - vm = { - result: ko.observable('').extend({ required: true }) - }; - ko.validation.init({ decorateInputElement: true }, true); + var $input = $('#testInput2'), + vm = { + result: ko.observable('').extend({ required: true }) + }; + ko.validation.init({ decorateInputElement: true }, true); - vm.result.isModified(true); //fake a modification + vm.result.isModified(true); //fake a modification - applyTestBindings(vm); + applyTestBindings(vm); - assert.ok(!vm.result.isValid(), 'Should initially be invalid'); - assert.ok($input.hasClass('validationElement'), 'Validation class should have been added'); + assert.ok(!vm.result.isValid(), 'Should initially be invalid'); + assert.ok($input.hasClass('validationElement'), 'Validation class should have been added'); - $input.prop('checked', true); - $input.click(); //trigger the validation + $input.prop('checked', true); + $input.click(); //trigger the validation - assert.equal(vm.result(), 'two', 'Value should have changed'); - assert.ok(vm.result.isValid(), 'Should now be valid'); - assert.ok(!$input.hasClass('validationElement'), 'Validation class should have been removed'); + assert.equal(vm.result(), 'two', 'Value should have changed'); + assert.ok(vm.result.isValid(), 'Should now be valid'); + assert.ok(!$input.hasClass('validationElement'), 'Validation class should have been removed'); }); QUnit.test('textInput Binding Works', function(assert) { - if (!ko.bindingHandlers.textInput) { - // 'textInput binding not supported (ko.version < 3.2). - assert.ok(true, 'textInput binding is available in ko >= 3.2. The test will be skipped.'); - return; - } - addTestHtml(''); + if (!ko.bindingHandlers.textInput) { + // 'textInput binding not supported (ko.version < 3.2). + assert.ok(true, 'textInput binding is available in ko >= 3.2. The test will be skipped.'); + return; + } + addTestHtml(''); - var vm = { - firstName: ko.observable('').extend({ required: true }) - }; + var vm = { + firstName: ko.observable('').extend({ required: true }) + }; - applyTestBindings(vm); + applyTestBindings(vm); - var $testInput = $('#myTestInput'); + var $testInput = $('#myTestInput'); - $testInput.val('a'); //set it - $testInput.change(); //trigger change event - assert.ok(vm.firstName.isValid(), 'First Name is Valid'); + $testInput.val('a'); //set it + $testInput.change(); //trigger change event + assert.ok(vm.firstName.isValid(), 'First Name is Valid'); - $testInput.val(''); //set it - $testInput.change(); //trigger change event - assert.ok(!vm.firstName.isValid(), 'First Name is NOT Valid'); + $testInput.val(''); //set it + $testInput.change(); //trigger change event + assert.ok(!vm.firstName.isValid(), 'First Name is NOT Valid'); - var msg = $testInput.siblings().first().text(); + var msg = $testInput.siblings().first().text(); - assert.equal(msg, 'This field is required.', msg); + assert.equal(msg, 'This field is required.', msg); }); QUnit.test('selectedOptions Binding Works', function(assert) { - addTestHtml(''); - - var vm = { - availableNames: ko.observableArray([ - {name: 'First'}, - {name: 'Second'}, - {name: 'Third'} - ]), - selectedNames: ko.observableArray() - .extend({ - validation: { - validator: function(value) { - return value.length > 0; - }, - message: 'Please select at least one item.' - } - }) - }; - - applyTestBindings(vm); - - var $testInput = $('#myTestInput'); - - $testInput.val('First'); - $testInput.change(); - assert.ok(vm.selectedNames.isValid(), 'selectedNames is Valid'); - - $testInput.val(''); - $testInput.change(); - assert.ok(!vm.selectedNames.isValid(), 'selectedNames is NOT Valid'); - - var msg = $testInput.siblings().first().text(); - assert.equal(msg, 'Please select at least one item.', msg); + addTestHtml(''); + + var vm = { + availableNames: ko.observableArray([ + {name: 'First'}, + {name: 'Second'}, + {name: 'Third'} + ]), + selectedNames: ko.observableArray() + .extend({ + validation: { + validator: function(value) { + return value.length > 0; + }, + message: 'Please select at least one item.' + } + }) + }; + + applyTestBindings(vm); + + var $testInput = $('#myTestInput'); + + $testInput.val('First'); + $testInput.change(); + assert.ok(vm.selectedNames.isValid(), 'selectedNames is Valid'); + + $testInput.val(''); + $testInput.change(); + assert.ok(!vm.selectedNames.isValid(), 'selectedNames is NOT Valid'); + + var msg = $testInput.siblings().first().text(); + assert.equal(msg, 'Please select at least one item.', msg); }); QUnit.test('Issue #277 - parseInputAttributes does not duplicate rules when parseInputAttributes=true', function(assert) { - var done = assert.async(); + var done = assert.async(); - ko.validation.init({parseInputAttributes: true, writeInputAttributes: false}, true); + ko.validation.init({parseInputAttributes: true, writeInputAttributes: false}, true); - var testObj = ko.observable('').extend({required: true, email: true}); - addTestHtml(''); - applyTestBindings({ email: testObj }); + var testObj = ko.observable('').extend({required: true, email: true}); + addTestHtml(''); + applyTestBindings({ email: testObj }); - setTimeout(function() { - assert.equal(testObj.rules().length, 2, 'rules are not duplicated'); - assert.equal(testObj.error(), 'This field is required.'); + setTimeout(function() { + assert.equal(testObj.rules().length, 2, 'rules are not duplicated'); + assert.equal(testObj.error(), 'This field is required.'); - testObj('abc'); - assert.equal(testObj.error(), 'Please enter a proper email address.'); + testObj('abc'); + assert.equal(testObj.error(), 'Please enter a proper email address.'); - done(); - }, 1); + done(); + }, 1); }); QUnit.test('Issue #277 - parseInputAttributes does not duplicate rules when parseInputAttributes=true', function(assert) { - var done = assert.async(); + var done = assert.async(); - ko.validation.init({parseInputAttributes: true, writeInputAttributes: true}, true); + ko.validation.init({parseInputAttributes: true, writeInputAttributes: true}, true); - var testObj = ko.observable('').extend({required: true, email: true}); - addTestHtml(''); - applyTestBindings({ email: testObj }); + var testObj = ko.observable('').extend({required: true, email: true}); + addTestHtml(''); + applyTestBindings({ email: testObj }); - setTimeout(function() { - assert.equal(testObj.rules().length, 2, 'rules are not duplicated'); - assert.equal(testObj.error(), 'This field is required.'); + setTimeout(function() { + assert.equal(testObj.rules().length, 2, 'rules are not duplicated'); + assert.equal(testObj.error(), 'This field is required.'); - testObj('abc'); - assert.equal(testObj.error(), 'Please enter a proper email address.'); + testObj('abc'); + assert.equal(testObj.error(), 'Please enter a proper email address.'); - done(); - }, 1); + done(); + }, 1); }); QUnit.test('Issue #526 - validation cannot be removed from attached observable', function(assert) { - var testObj = ko.observable(1).extend({ min: 2 }); + var testObj = ko.observable(1).extend({ min: 2 }); - addTestHtml(''); - applyTestBindings({value: testObj}); + addTestHtml(''); + applyTestBindings({value: testObj}); - assert.violatesMinRule(testObj, 1, 2); - assert.ok(ko.validation.utils.isValidatable(testObj)); + assert.violatesMinRule(testObj, 1, 2); + assert.ok(ko.validation.utils.isValidatable(testObj)); - testObj.extend({validatable: false}); - assert.equal(ko.validation.utils.isValidatable(testObj), false); + testObj.extend({validatable: false}); + assert.equal(ko.validation.utils.isValidatable(testObj), false); }); //#region Inserting Messages QUnit.test('Inserting Messages Works', function(assert) { - addTestHtml(''); + addTestHtml(''); - var vm = { - firstName: ko.observable('').extend({ required: true }) - }; + var vm = { + firstName: ko.observable('').extend({ required: true }) + }; - applyTestBindings(vm); + applyTestBindings(vm); - var $testInput = $('#myTestInput').val('a').change().val('').change(); - assert.ok(!vm.firstName.isValid(), 'First Name is NOT Valid'); + var $testInput = $('#myTestInput').val('a').change().val('').change(); + assert.ok(!vm.firstName.isValid(), 'First Name is NOT Valid'); - var msg = $testInput.siblings().first().text(); - assert.equal(msg, 'This field is required.', msg); + var msg = $testInput.siblings().first().text(); + assert.equal(msg, 'This field is required.', msg); }); QUnit.test('Inserting Messages with HTML Works', function(assert) { - ko.validation.init({ - allowHtmlMessages: true - }, true); + ko.validation.init({ + allowHtmlMessages: true + }, true); - addTestHtml(''); + addTestHtml(''); - var vm = { - firstName: ko.observable('').extend({ required: {message: 'This field is required.'} }) - }; + var vm = { + firstName: ko.observable('').extend({ required: {message: 'This field is required.'} }) + }; - applyTestBindings(vm); + applyTestBindings(vm); - var $testInput = $('#myTestInput').val('a').change().val('').change(); - assert.ok(!vm.firstName.isValid(), 'First Name is NOT Valid'); + var $testInput = $('#myTestInput').val('a').change().val('').change(); + assert.ok(!vm.firstName.isValid(), 'First Name is NOT Valid'); - var msg = $testInput.siblings().first().html(); - assert.equal(msg, 'This field is required.', msg); + var msg = $testInput.siblings().first().html(); + assert.equal(msg, 'This field is required.', msg); }); //#endregion @@ -223,50 +222,50 @@ QUnit.test('Inserting Messages with HTML Works', function(assert) { QUnit.test('Decorating Elements Works', function(assert) { - addTestHtml(''); + addTestHtml(''); - var vm = { - firstName: ko.observable('').extend({ required: true }) - }; + var vm = { + firstName: ko.observable('').extend({ required: true }) + }; - // make sure the options are ok. - ko.validation.init({ - decorateInputElement: true - }, true); + // make sure the options are ok. + ko.validation.init({ + decorateInputElement: true + }, true); - applyTestBindings(vm); + applyTestBindings(vm); - var $testInput = $('#myTestInput'); - assert.ok(!$testInput.hasClass('validationElement'), "CSS class shouldn't present"); + var $testInput = $('#myTestInput'); + assert.ok(!$testInput.hasClass('validationElement'), "CSS class shouldn't present"); - $testInput.val('a').change().val('').change(); - assert.ok($testInput.hasClass('validationElement'), 'CSS class should present'); + $testInput.val('a').change().val('').change(); + assert.ok($testInput.hasClass('validationElement'), 'CSS class should present'); }); QUnit.test('Decorating Elements On Modified Works', function(assert) { - addTestHtml(''); + addTestHtml(''); - var vm = { - firstName: ko.observable('').extend({ required: true }) - }; + var vm = { + firstName: ko.observable('').extend({ required: true }) + }; - // make sure the options are ok. - ko.validation.init({ - decorateInputElement: true, - decorateElementOnModified: false - }, true); + // make sure the options are ok. + ko.validation.init({ + decorateInputElement: true, + decorateElementOnModified: false + }, true); - applyTestBindings(vm); + applyTestBindings(vm); - var $testInput = $('#myTestInput'); + var $testInput = $('#myTestInput'); - assert.ok($testInput.hasClass('validationElement'), 'CSS class should present'); + assert.ok($testInput.hasClass('validationElement'), 'CSS class should present'); - $testInput.val('a'); //set it - $testInput.change(); //trigger change event + $testInput.val('a'); //set it + $testInput.change(); //trigger change event - assert.ok(!$testInput.hasClass('validationElement'), "CSS class shouldn't present"); + assert.ok(!$testInput.hasClass('validationElement'), "CSS class shouldn't present"); }); //#endregion @@ -275,69 +274,69 @@ QUnit.test('Decorating Elements On Modified Works', function(assert) { QUnit.test('Showing Errors As Titles Works', function(assert) { - addTestHtml(''); + addTestHtml(''); - var vm = { - firstName: ko.observable('').extend({ required: true }) - }; + var vm = { + firstName: ko.observable('').extend({ required: true }) + }; - // make sure the options are ok. - ko.validation.init({ - errorsAsTitleOnModified: true, - decorateInputElement: true - }, true); + // make sure the options are ok. + ko.validation.init({ + errorsAsTitleOnModified: true, + decorateInputElement: true + }, true); - applyTestBindings(vm); + applyTestBindings(vm); - var $testInput = $('#myTestInput'); + var $testInput = $('#myTestInput'); - $testInput.val('a'); //set it - $testInput.change(); //trigger change event + $testInput.val('a'); //set it + $testInput.change(); //trigger change event - $testInput.val(''); //set it - $testInput.change(); //trigger change event + $testInput.val(''); //set it + $testInput.change(); //trigger change event - var isValid = vm.firstName.isValid(); + var isValid = vm.firstName.isValid(); - assert.ok(!isValid, 'First Name is NOT Valid'); + assert.ok(!isValid, 'First Name is NOT Valid'); - var msg = $testInput.attr('title'); + var msg = $testInput.attr('title'); - assert.equal(msg, 'This field is required.', msg); + assert.equal(msg, 'This field is required.', msg); }); QUnit.test('Original titles are restored', function(assert) { - addTestHtml(''); + addTestHtml(''); - var vm = { - firstName: ko.observable('').extend({ required: true }) - }; + var vm = { + firstName: ko.observable('').extend({ required: true }) + }; - // make sure the options are ok. - ko.validation.init({ - errorsAsTitleOnModified: true, - decorateInputElement: true - }, true); + // make sure the options are ok. + ko.validation.init({ + errorsAsTitleOnModified: true, + decorateInputElement: true + }, true); - applyTestBindings(vm); + applyTestBindings(vm); - var $testInput = $('#myTestInput'); + var $testInput = $('#myTestInput'); - $testInput.val('a'); //set it - $testInput.change(); //trigger change event + $testInput.val('a'); //set it + $testInput.change(); //trigger change event - $testInput.val(''); //set it - $testInput.change(); //trigger change event + $testInput.val(''); //set it + $testInput.change(); //trigger change event - var msg = $testInput.attr('title'); - assert.equal(msg, 'This field is required.', msg); + var msg = $testInput.attr('title'); + assert.equal(msg, 'This field is required.', msg); - $testInput.val('a'); //set it - $testInput.change(); //trigger change event + $testInput.val('a'); //set it + $testInput.change(); //trigger change event - msg = $testInput.attr('title'); - assert.equal(msg, 'my-orig-title', msg); + msg = $testInput.attr('title'); + assert.equal(msg, 'my-orig-title', msg); }); @@ -377,99 +376,99 @@ QUnit.test('Original titles are restored to blank', function(assert) { QUnit.test('Original titles are restored with multiple validators, too', function(assert) { - addTestHtml(''); + addTestHtml(''); - var vm = { - firstName: ko.observable('').extend({ required: true, minLength: 2 }) - }; + var vm = { + firstName: ko.observable('').extend({ required: true, minLength: 2 }) + }; - // make sure the options are ok. - ko.validation.init({ - errorsAsTitleOnModified: true, - decorateInputElement: true - }, true); + // make sure the options are ok. + ko.validation.init({ + errorsAsTitleOnModified: true, + decorateInputElement: true + }, true); - applyTestBindings(vm); + applyTestBindings(vm); - var $testInput = $('#myTestInput'); + var $testInput = $('#myTestInput'); - $testInput.val('aa'); //set it - $testInput.change(); //trigger change event + $testInput.val('aa'); //set it + $testInput.change(); //trigger change event - $testInput.val(''); //set it - $testInput.change(); //trigger change event + $testInput.val(''); //set it + $testInput.change(); //trigger change event - var msg = $testInput.attr('title'); - assert.equal(msg, 'This field is required.', msg); + var msg = $testInput.attr('title'); + assert.equal(msg, 'This field is required.', msg); - $testInput.val('a'); //set it - $testInput.change(); //trigger change event + $testInput.val('a'); //set it + $testInput.change(); //trigger change event - msg = $testInput.attr('title'); - assert.equal(msg, 'Please enter at least 2 characters.', msg); + msg = $testInput.attr('title'); + assert.equal(msg, 'Please enter at least 2 characters.', msg); - $testInput.val('aa'); //set it - $testInput.change(); //trigger change event + $testInput.val('aa'); //set it + $testInput.change(); //trigger change event - msg = $testInput.attr('title'); - assert.equal(msg, 'my-orig-title', msg); + msg = $testInput.attr('title'); + assert.equal(msg, 'my-orig-title', msg); }); QUnit.test('Showing Errors As Titles is disabled successfully', function(assert) { - addTestHtml(''); + addTestHtml(''); - var vm = { - firstName: ko.observable('').extend({ required: true }) - }; + var vm = { + firstName: ko.observable('').extend({ required: true }) + }; - // make sure the options are ok. - ko.validation.init({ - errorsAsTitleOnModified: true, - decorateInputElement: true, + // make sure the options are ok. + ko.validation.init({ + errorsAsTitleOnModified: true, + decorateInputElement: true, errorsAsTitle: false - }, true); + }, true); - applyTestBindings(vm); + applyTestBindings(vm); - var $testInput = $('#myTestInput'); + var $testInput = $('#myTestInput'); - $testInput.val('a'); //set it - $testInput.change(); //trigger change event + $testInput.val('a'); //set it + $testInput.change(); //trigger change event - $testInput.val(''); //set it - $testInput.change(); //trigger change event + $testInput.val(''); //set it + $testInput.change(); //trigger change event - var isValid = vm.firstName.isValid(); + var isValid = vm.firstName.isValid(); - assert.ok(!isValid, 'First Name is NOT Valid'); + assert.ok(!isValid, 'First Name is NOT Valid'); - var msg = $testInput.attr('title'); + var msg = $testInput.attr('title'); - assert.notEqual(msg, 'This field is required.', msg); + assert.notEqual(msg, 'This field is required.', msg); }); QUnit.test('Removing error message from title when isModified is reset', function(assert) { - addTestHtml(''); + addTestHtml(''); - var vm = { - prop: ko.observable('').extend({ required: true }) - }; + var vm = { + prop: ko.observable('').extend({ required: true }) + }; - // make sure the options are ok. - ko.validation.init({ - errorsAsTitleOnModified: true, - decorateInputElement: true, - errorsAsTitle: false - }, true); + // make sure the options are ok. + ko.validation.init({ + errorsAsTitleOnModified: true, + decorateInputElement: true, + errorsAsTitle: false + }, true); - applyTestBindings(vm); + applyTestBindings(vm); - vm.prop('valid').prop(''); - vm.prop.isModified(false); + vm.prop('valid').prop(''); + vm.prop.isModified(false); - assert.ok(!$('#myTestInput').attr('title')); + assert.ok(!$('#myTestInput').attr('title')); }); //#endregion @@ -477,894 +476,894 @@ QUnit.test('Removing error message from title when isModified is reset', functio //#region Validation Option Tests QUnit.test('Validation Options - Basic Tests', function(assert) { - var testHtml = '
                  '; - addTestHtml(testHtml); + var testHtml = '
                  '; + addTestHtml(testHtml); - var vm = { - firstName: ko.observable('').extend({ required: true }) - }; + var vm = { + firstName: ko.observable('').extend({ required: true }) + }; - applyTestBindings(vm); + applyTestBindings(vm); - var $testInput = $('#myTestInput') - .val('a').change() - .val('').change(); + var $testInput = $('#myTestInput') + .val('a').change() + .val('').change(); - assert.violatesRequiredRule(vm.firstName, ''); + assert.violatesRequiredRule(vm.firstName, ''); - var noMsgs = $testInput.siblings().length; - assert.equal(noMsgs, 0, 'No Messages were inserted'); + var noMsgs = $testInput.siblings().length; + assert.equal(noMsgs, 0, 'No Messages were inserted'); }); QUnit.test('Validation Options - Nested Test', function(assert) { - var testHtml = '
                  ' + - '' + - '
                  ' + - '' + - '
                  ' + - '
                  '; + var testHtml = '
                  ' + + '' + + '
                  ' + + '' + + '
                  ' + + '
                  '; - addTestHtml(testHtml); + addTestHtml(testHtml); - var vm = { - firstName: ko.observable('').extend({ required: true }), - someObj: { - lastName: ko.observable().extend({ minLength : 2 }) - } - }; + var vm = { + firstName: ko.observable('').extend({ required: true }), + someObj: { + lastName: ko.observable().extend({ minLength : 2 }) + } + }; - applyTestBindings(vm); + applyTestBindings(vm); - var $testInput = $('#myLastName').val('a').change(); - assert.violatesMinLengthRule(vm.someObj.lastName, 'a', 2); + var $testInput = $('#myLastName').val('a').change(); + assert.violatesMinLengthRule(vm.someObj.lastName, 'a', 2); - var noMsgs = $testInput.siblings().length; - assert.equal(noMsgs, 0, 'No Messages were inserted'); + var noMsgs = $testInput.siblings().length; + assert.equal(noMsgs, 0, 'No Messages were inserted'); }); QUnit.test('Validation Options - Options only apply to their HTML Contexts', function(assert) { - var testHtml = '
                  ' + - '
                  ' + - '
                  ' + - '' + - '
                  ' + - '
                  ' + - '' + - '
                  '; - addTestHtml(testHtml); - - var vm = { - firstName: ko.observable('a').extend({ required: true }), - someObj: { - lastName: ko.observable().extend({ minLength: 2 }) - } - }; - - applyTestBindings(vm); - - var $testInput = $('#myLastName').val('a').change(); - assert.violatesMinLengthRule(vm.someObj.lastName, 'a', 2); - - var noMsgs = $testInput.siblings().length; - assert.equal(noMsgs, 0, 'No Messages were inserted'); - - var $firstName = $('#myFirstName').val('').change(); - assert.violatesRequiredRule(vm.firstName, ''); - - var insertMsgCt = $firstName.siblings('span').length; - assert.equal(insertMsgCt, 1, 'Should have inserted 1 message beside the first name!'); + var testHtml = '
                  ' + + '
                  ' + + '
                  ' + + '' + + '
                  ' + + '
                  ' + + '' + + '
                  '; + addTestHtml(testHtml); + + var vm = { + firstName: ko.observable('a').extend({ required: true }), + someObj: { + lastName: ko.observable().extend({ minLength: 2 }) + } + }; + + applyTestBindings(vm); + + var $testInput = $('#myLastName').val('a').change(); + assert.violatesMinLengthRule(vm.someObj.lastName, 'a', 2); + + var noMsgs = $testInput.siblings().length; + assert.equal(noMsgs, 0, 'No Messages were inserted'); + + var $firstName = $('#myFirstName').val('').change(); + assert.violatesRequiredRule(vm.firstName, ''); + + var insertMsgCt = $firstName.siblings('span').length; + assert.equal(insertMsgCt, 1, 'Should have inserted 1 message beside the first name!'); }); QUnit.test('Issue #43 & #47 - Error messages are not switched correctly', function(assert) { - var vm = { - testObj: ko.observable().extend({ min: 1, max: 100 }), - dummyProp: ko.observable().extend({ required: true }) - }; + var vm = { + testObj: ko.observable().extend({ min: 1, max: 100 }), + dummyProp: ko.observable().extend({ required: true }) + }; - vm.errors = ko.validation.group(vm); + vm.errors = ko.validation.group(vm); - // setup the html - addTestHtml(''); - applyTestBindings(vm); + // setup the html + addTestHtml(''); + applyTestBindings(vm); - var $msg = $('#testMessage'); + var $msg = $('#testMessage'); - vm.testObj(-1); // should invalidate the min rule - assert.violatesMinRule(vm.testObj, -1, 1); - assert.equal(vm.testObj.error(), $msg.text(), 'Min rule was correctly triggered'); + vm.testObj(-1); // should invalidate the min rule + assert.violatesMinRule(vm.testObj, -1, 1); + assert.equal(vm.testObj.error(), $msg.text(), 'Min rule was correctly triggered'); - vm.testObj(101); // should invalidate the max rule - assert.violatesMaxRule(vm.testObj, 101, 100); - assert.equal(vm.testObj.error(), $msg.text(), 'Max rule was correctly triggered'); + vm.testObj(101); // should invalidate the max rule + assert.violatesMaxRule(vm.testObj, 101, 100); + assert.equal(vm.testObj.error(), $msg.text(), 'Max rule was correctly triggered'); }); QUnit.test('Issue #44 - Validation Element - Is Valid Test', function(assert) { - var vm = { - testObj: ko.observable().extend({ min: 1, max: 100 }) - }; + var vm = { + testObj: ko.observable().extend({ min: 1, max: 100 }) + }; - // setup the html - addTestHtml(''); + // setup the html + addTestHtml(''); - // make sure we allow element decorations - ko.validation.init({ decorateInputElement: true }, true); + // make sure we allow element decorations + ko.validation.init({ decorateInputElement: true }, true); - applyTestBindings(vm); + applyTestBindings(vm); - var $el = $('#testElement'); - assert.ok(!$el.hasClass('validationElement'), 'Does not have the validation class'); + var $el = $('#testElement'); + assert.ok(!$el.hasClass('validationElement'), 'Does not have the validation class'); - vm.testObj(2); // should validate the min rule + vm.testObj(2); // should validate the min rule - assert.ok(vm.testObj.isValid(), 'Object is valid'); - assert.ok(!$el.hasClass('validationElement'), 'Correctly does not have the validation class'); + assert.ok(vm.testObj.isValid(), 'Object is valid'); + assert.ok(!$el.hasClass('validationElement'), 'Correctly does not have the validation class'); }); QUnit.test('Issue #44 - Validation Element - Is Invalid Test', function(assert) { - var vm = { - testObj: ko.observable().extend({ min: 1, max: 100 }) - }; + var vm = { + testObj: ko.observable().extend({ min: 1, max: 100 }) + }; - // setup the html - addTestHtml(''); + // setup the html + addTestHtml(''); - // make sure we allow element decorations - ko.validation.init({ decorateInputElement: true }, true); + // make sure we allow element decorations + ko.validation.init({ decorateInputElement: true }, true); - applyTestBindings(vm); + applyTestBindings(vm); - var $el = $('#testElement'); - assert.ok(!$el.hasClass('validationElement'), 'Does not have the validation class'); + var $el = $('#testElement'); + assert.ok(!$el.hasClass('validationElement'), 'Does not have the validation class'); - vm.testObj(-1); // should invalidate the min rule + vm.testObj(-1); // should invalidate the min rule - assert.ok(!vm.testObj.isValid(), 'Object is not valid'); - assert.ok($el.hasClass('validationElement'), 'Correctly does have the validation class'); + assert.ok(!vm.testObj.isValid(), 'Object is not valid'); + assert.ok($el.hasClass('validationElement'), 'Correctly does have the validation class'); }); QUnit.test('Issue #519 - validationElement can be applied before element is validatable', function(assert) { - var vm = { - testObj: ko.observable() - }; + var vm = { + testObj: ko.observable() + }; - addTestHtml(''); - applyTestBindings(vm); + addTestHtml(''); + applyTestBindings(vm); - assert.strictEqual(!!$("#testElement").attr("class"), false); - assert.ok(!ko.validation.utils.isValidatable(vm.testObj)); + assert.strictEqual(!!$("#testElement").attr("class"), false); + assert.ok(!ko.validation.utils.isValidatable(vm.testObj)); - vm.testObj.extend({ required: true }); - vm.testObj(null); - assert.ok(ko.validation.utils.isValidatable(vm.testObj)); - assert.strictEqual($("#testElement").attr("class"), "validationElement"); - assert.strictEqual($("#testElement").attr("title"), "This field is required."); + vm.testObj.extend({ required: true }); + vm.testObj(null); + assert.ok(ko.validation.utils.isValidatable(vm.testObj)); + assert.strictEqual($("#testElement").attr("class"), "validationElement"); + assert.strictEqual($("#testElement").attr("title"), "This field is required."); - vm.testObj.extend({ validatable: false }); - assert.ok(!ko.validation.utils.isValidatable(vm.testObj)); - assert.strictEqual($("#testElement").attr("title"), undefined); + vm.testObj.extend({ validatable: false }); + assert.ok(!ko.validation.utils.isValidatable(vm.testObj)); + assert.strictEqual($("#testElement").attr("title"), undefined); }); QUnit.test('Issue #519 - validationMessage can be applied before element is validatable', function(assert) { - var vm = { - testObj: ko.observable() - }; + var vm = { + testObj: ko.observable() + }; - addTestHtml(''); - applyTestBindings(vm); + addTestHtml(''); + applyTestBindings(vm); - assert.ok(!$("#testElement").is(':visible')); - assert.ok(!ko.validation.utils.isValidatable(vm.testObj)); + assert.ok(!$("#testElement").is(':visible')); + assert.ok(!ko.validation.utils.isValidatable(vm.testObj)); - vm.testObj.extend({ required: true }); - vm.testObj(null); - assert.ok(ko.validation.utils.isValidatable(vm.testObj)); - assert.ok($("#testElement").is(':visible')); - assert.strictEqual($("#testElement").html(), "This field is required."); + vm.testObj.extend({ required: true }); + vm.testObj(null); + assert.ok(ko.validation.utils.isValidatable(vm.testObj)); + assert.ok($("#testElement").is(':visible')); + assert.strictEqual($("#testElement").html(), "This field is required."); - vm.testObj.extend({ validatable: false }); - assert.ok(!ko.validation.utils.isValidatable(vm.testObj)); - assert.strictEqual($("#testElement").html(), ""); + vm.testObj.extend({ validatable: false }); + assert.ok(!ko.validation.utils.isValidatable(vm.testObj)); + assert.strictEqual($("#testElement").html(), ""); }); QUnit.test('Issue #481 - writeInputAttributes doesn\'t unwrap params to sync attribute', function(assert) { - var minValue = ko.observable(4); - var testObj = ko.observable(10).extend({min: minValue}); + var minValue = ko.observable(4); + var testObj = ko.observable(10).extend({min: minValue}); - var $element = jQuery(''); - addTestHtml($element); - ko.validation.init({writeInputAttributes: true}, true); - applyTestBindings({value: testObj}); + var $element = jQuery(''); + addTestHtml($element); + ko.validation.init({writeInputAttributes: true}, true); + applyTestBindings({value: testObj}); - assert.strictEqual($element.attr('min'), '4', 'min attribute is written'); - minValue(15); - assert.strictEqual($element.attr('min'), '15', 'min attribute is written'); + assert.strictEqual($element.attr('min'), '4', 'min attribute is written'); + minValue(15); + assert.strictEqual($element.attr('min'), '15', 'min attribute is written'); }); QUnit.test('Issue #80 - Write HTML5 Validation Attributes programmatically', function(assert) { - var vm = { - testObj: ko.observable(15).extend({ min: 1, max: 100, required: true, step: 2, pattern: /blah/i }) - }; + var vm = { + testObj: ko.observable(15).extend({ min: 1, max: 100, required: true, step: 2, pattern: /blah/i }) + }; - // setup the html - addTestHtml(''); + // setup the html + addTestHtml(''); - // make sure we allow element decorations - ko.validation.init({ - decorateInputElement: true, - writeInputAttributes: true - }, true); + // make sure we allow element decorations + ko.validation.init({ + decorateInputElement: true, + writeInputAttributes: true + }, true); - applyTestBindings(vm); + applyTestBindings(vm); - var $el = $('#testElement'); - var tests = {}; + var $el = $('#testElement'); + var tests = {}; - ko.utils.arrayForEach(['required', 'min', 'max', 'step', 'pattern'], function(attr) { - tests[attr] = $el.attr(attr); - }); + ko.utils.arrayForEach(['required', 'min', 'max', 'step', 'pattern'], function(attr) { + tests[attr] = $el.attr(attr); + }); - assert.ok(tests.required, 'Required Found'); - assert.strictEqual(tests.min, '1', 'Min Found'); - assert.strictEqual(tests.max, '100', 'Max Found'); - assert.strictEqual(tests.step, '2', 'Step Found'); - assert.strictEqual(tests.pattern, 'blah', 'Pattern Found'); + assert.ok(tests.required, 'Required Found'); + assert.strictEqual(tests.min, '1', 'Min Found'); + assert.strictEqual(tests.max, '100', 'Max Found'); + assert.strictEqual(tests.step, '2', 'Step Found'); + assert.strictEqual(tests.pattern, 'blah', 'Pattern Found'); }); QUnit.test('Issue #400 - Write HTML5 Validation Attributes fails when anonymous rules are used', function(assert) { - var vm = { - testObj: ko.observable(15).extend({required: true}).extend({ - validation: [{ - validator: function(value, params) { - return parseInt(value, 10) === params; - }, - message: function(params) { - return 'Value must be equal to ' + params; - }, - params: 1 - }] - }) - }; - - // setup the html - addTestHtml(''); - - // make sure we allow element decorations - ko.validation.init({ - decorateInputElement: true, - writeInputAttributes: true - }, true); - - applyTestBindings(vm); - - var $el = $('#testElement'); - var tests = {}; - - ko.utils.arrayForEach(['required', 'min', 'max', 'step', 'pattern'], function(attr) { - tests[attr] = $el.attr(attr); - }); - - assert.ok(tests.required, 'Required Found'); - assert.observableIsNotValid(vm.testObj, 15, 'Value must be equal to 1'); + var vm = { + testObj: ko.observable(15).extend({required: true}).extend({ + validation: [{ + validator: function(value, params) { + return parseInt(value, 10) === params; + }, + message: function(params) { + return 'Value must be equal to ' + params; + }, + params: 1 + }] + }) + }; + + // setup the html + addTestHtml(''); + + // make sure we allow element decorations + ko.validation.init({ + decorateInputElement: true, + writeInputAttributes: true + }, true); + + applyTestBindings(vm); + + var $el = $('#testElement'); + var tests = {}; + + ko.utils.arrayForEach(['required', 'min', 'max', 'step', 'pattern'], function(attr) { + tests[attr] = $el.attr(attr); + }); + + assert.ok(tests.required, 'Required Found'); + assert.observableIsNotValid(vm.testObj, 15, 'Value must be equal to 1'); }); QUnit.test('Issue #80 - HTML5 attributes - pattern', function(assert) { - var pattern = /something/i; - var patternString = 'something'; + var pattern = /something/i; + var patternString = 'something'; - var vm = { - testObj: ko.observable('something').extend({ - pattern: pattern - }) - }; + var vm = { + testObj: ko.observable('something').extend({ + pattern: pattern + }) + }; - // setup the html - addTestHtml(''); + // setup the html + addTestHtml(''); - // make sure we allow element decorations - ko.validation.init({ - decorateInputElement: true, - writeInputAttributes: true - }, true); + // make sure we allow element decorations + ko.validation.init({ + decorateInputElement: true, + writeInputAttributes: true + }, true); - applyTestBindings(vm); + applyTestBindings(vm); - var $el = $('#testElement'); - var el = $el.get(0); + var $el = $('#testElement'); + var el = $el.get(0); - var param = $el.attr('pattern'); + var param = $el.attr('pattern'); - // fire the validity check event - el.checkValidity(); + // fire the validity check event + el.checkValidity(); - assert.strictEqual(param, patternString, 'Patterns Match'); - assert.ok(vm.testObj.isValid(), 'Observable is valid'); - assert.ok(el.validity.valid, 'Element is showing it is valid'); - assert.strictEqual(vm.testObj(), 'something', 'Observable still works'); + assert.strictEqual(param, patternString, 'Patterns Match'); + assert.ok(vm.testObj.isValid(), 'Observable is valid'); + assert.ok(el.validity.valid, 'Element is showing it is valid'); + assert.strictEqual(vm.testObj(), 'something', 'Observable still works'); }); QUnit.module('HTML5 UI Tests', { - afterEach: function() { - var $element = $('#testContainer'); - ko.cleanNode($element[0]); - $element.empty(); - ko.validation.reset(); - } + afterEach: function() { + var $element = $('#testContainer'); + ko.cleanNode($element[0]); + $element.empty(); + ko.validation.reset(); + } }); QUnit.test('HTML5 Input types', function(assert) { - var done = assert.async(); - assert.expect(3); - - var vm = { - invalidEmail: ko.validatedObservable('invalidEmail'), - invalidDate: ko.validatedObservable('no date'), - invalidNumber: ko.validatedObservable('invalidNumber') - }; - - // setup the html - addTestHtml('' + - ''+ - ''); - - // make sure we parse element attributes - ko.validation.init({parseInputAttributes: true}, true); - - applyTestBindings(vm); - - // The validators for the HTML5 Input types are applied asynchronously, - // so we need to wait until the validators have been applied. This is - // done by checking to make sure that the rule has been added to the rules - // list of each observable. - var intervalsWaited = 0; - var intervalId = setInterval(function() { - if (intervalsWaited++ > 1000) { - clearInterval(intervalId); - assert.ok(false, 'Async HTML5 Input validators did not apply within a reasonable amount of time'); - } - var validatorsReady = - vm.invalidEmail.rules().length > 0 && - vm.invalidDate.rules().length > 0 && - vm.invalidNumber.rules().length > 0; - - if (validatorsReady) { - clearInterval(intervalId); - assert.ok(!vm.invalidEmail.isValid(), 'Expected email to be considered as invalid.'); - assert.ok(!vm.invalidDate.isValid(), 'Expected date to be considered as invalid.'); - assert.ok(!vm.invalidNumber.isValid(), 'Expected date to be considered as invalid.'); - - done(); - } - }, 1); + var done = assert.async(); + assert.expect(3); + + var vm = { + invalidEmail: ko.validatedObservable('invalidEmail'), + invalidDate: ko.validatedObservable('no date'), + invalidNumber: ko.validatedObservable('invalidNumber') + }; + + // setup the html + addTestHtml('' + + ''+ + ''); + + // make sure we parse element attributes + ko.validation.init({parseInputAttributes: true}, true); + + applyTestBindings(vm); + + // The validators for the HTML5 Input types are applied asynchronously, + // so we need to wait until the validators have been applied. This is + // done by checking to make sure that the rule has been added to the rules + // list of each observable. + var intervalsWaited = 0; + var intervalId = setInterval(function() { + if (intervalsWaited++ > 1000) { + clearInterval(intervalId); + assert.ok(false, 'Async HTML5 Input validators did not apply within a reasonable amount of time'); + } + var validatorsReady = + vm.invalidEmail.rules().length > 0 && + vm.invalidDate.rules().length > 0 && + vm.invalidNumber.rules().length > 0; + + if (validatorsReady) { + clearInterval(intervalId); + assert.ok(!vm.invalidEmail.isValid(), 'Expected email to be considered as invalid.'); + assert.ok(!vm.invalidDate.isValid(), 'Expected date to be considered as invalid.'); + assert.ok(!vm.invalidNumber.isValid(), 'Expected date to be considered as invalid.'); + + done(); + } + }, 1); }); QUnit.test('min Attribute of 20 should fail for value of 8', function(assert) { - var done = assert.async(); - assert.expect(3); + var done = assert.async(); + assert.expect(3); - var vm = { - someNumber: ko.validatedObservable() - }; + var vm = { + someNumber: ko.validatedObservable() + }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({parseInputAttributes: true}, true); - applyTestBindings(vm); + ko.validation.init({parseInputAttributes: true}, true); + applyTestBindings(vm); - setTimeout(function() { - vm.someNumber(8); // should fail the max rule + setTimeout(function() { + vm.someNumber(8); // should fail the max rule - var el = $('#myTestInput'); + var el = $('#myTestInput'); - assert.ok(el, 'found element'); - assert.ok(!vm.someNumber.isValid(), 'Object is not valid'); - assert.equal(vm.someNumber.error(), 'Please enter a value greater than or equal to 20.', - 'Message needs to be formatted correctly'); + assert.ok(el, 'found element'); + assert.ok(!vm.someNumber.isValid(), 'Object is not valid'); + assert.equal(vm.someNumber.error(), 'Please enter a value greater than or equal to 20.', + 'Message needs to be formatted correctly'); - done(); - }, 1); + done(); + }, 1); }); QUnit.test('min Attribute of 20 should fail for value of "8"', function(assert) { - var done = assert.async(); - assert.expect(3); + var done = assert.async(); + assert.expect(3); - var vm = { - someNumber: ko.validatedObservable() - }; + var vm = { + someNumber: ko.validatedObservable() + }; - addTestHtml(''); - ko.validation.init({parseInputAttributes: true}, true); - applyTestBindings(vm); + addTestHtml(''); + ko.validation.init({parseInputAttributes: true}, true); + applyTestBindings(vm); - setTimeout(function() { - vm.someNumber('8'); // should fail the min rule + setTimeout(function() { + vm.someNumber('8'); // should fail the min rule - var el = $('#myTestInput'); + var el = $('#myTestInput'); - assert.ok(el, 'found element'); - assert.ok(!vm.someNumber.isValid(), "Object is not valid"); - assert.equal(vm.someNumber.error(), "Please enter a value greater than or equal to 20.", - 'Message needs to be formatted correctly'); + assert.ok(el, 'found element'); + assert.ok(!vm.someNumber.isValid(), "Object is not valid"); + assert.equal(vm.someNumber.error(), "Please enter a value greater than or equal to 20.", + 'Message needs to be formatted correctly'); - done(); - }, 1); + done(); + }, 1); }); QUnit.test('min Attribute of 20 should fail for value of "8" with text type', function(assert) { - var done = assert.async(); - assert.expect(3); + var done = assert.async(); + assert.expect(3); - var vm = { - someNumber: ko.validatedObservable() - }; + var vm = { + someNumber: ko.validatedObservable() + }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({parseInputAttributes: true}, true); - applyTestBindings(vm); + ko.validation.init({parseInputAttributes: true}, true); + applyTestBindings(vm); - setTimeout(function() { - vm.someNumber('8'); // should fail the min rule + setTimeout(function() { + vm.someNumber('8'); // should fail the min rule - var el = $('#myTestInput'); + var el = $('#myTestInput'); - assert.ok(el, 'found element'); - assert.ok(!vm.someNumber.isValid(), 'Object is not valid'); - assert.equal(vm.someNumber.error(), 'Please enter a value greater than or equal to 20.', - 'Message needs to be formatted correctly'); + assert.ok(el, 'found element'); + assert.ok(!vm.someNumber.isValid(), 'Object is not valid'); + assert.equal(vm.someNumber.error(), 'Please enter a value greater than or equal to 20.', + 'Message needs to be formatted correctly'); - done(); - }, 1); + done(); + }, 1); }); QUnit.test('min Attribute of 20 should pass for value of 110', function(assert) { - var done = assert.async(); - assert.expect(2); + var done = assert.async(); + assert.expect(2); - var vm = { - someNumber: ko.validatedObservable() - }; + var vm = { + someNumber: ko.validatedObservable() + }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({parseInputAttributes: true}, true); - applyTestBindings(vm); + ko.validation.init({parseInputAttributes: true}, true); + applyTestBindings(vm); - setTimeout(function() { - vm.someNumber(110); // should validate the min rule + setTimeout(function() { + vm.someNumber(110); // should validate the min rule - var el = $('#myTestInput'); + var el = $('#myTestInput'); - assert.ok(el, 'found element'); - assert.ok(vm.someNumber.isValid(), 'Object is valid'); + assert.ok(el, 'found element'); + assert.ok(vm.someNumber.isValid(), 'Object is valid'); - done(); - }, 1); + done(); + }, 1); }); QUnit.test('min Attribute of 20 should pass for value of "110"', function(assert) { - var done = assert.async(); - assert.expect(2); + var done = assert.async(); + assert.expect(2); - var vm = { - someNumber: ko.validatedObservable() - }; + var vm = { + someNumber: ko.validatedObservable() + }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({parseInputAttributes: true}, true); - applyTestBindings(vm); + ko.validation.init({parseInputAttributes: true}, true); + applyTestBindings(vm); - setTimeout(function() { - vm.someNumber('110'); // should validate the min rule + setTimeout(function() { + vm.someNumber('110'); // should validate the min rule - var el = $('#myTestInput'); + var el = $('#myTestInput'); - assert.ok(el, 'found element'); - assert.ok(vm.someNumber.isValid(), 'Object is valid'); + assert.ok(el, 'found element'); + assert.ok(vm.someNumber.isValid(), 'Object is valid'); - done(); - }, 1); + done(); + }, 1); }); QUnit.test('max Attribute of 30 should fail for value of 100', function(assert) { - var done = assert.async(); - assert.expect(3); + var done = assert.async(); + assert.expect(3); - var vm = { - someNumber: ko.validatedObservable() - }; + var vm = { + someNumber: ko.validatedObservable() + }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({parseInputAttributes: true}, true); - applyTestBindings(vm); + ko.validation.init({parseInputAttributes: true}, true); + applyTestBindings(vm); - setTimeout(function() { - vm.someNumber(100); // should fail the max rule + setTimeout(function() { + vm.someNumber(100); // should fail the max rule - var el = $('#myTestInput'); + var el = $('#myTestInput'); - assert.ok(el, 'found element'); - assert.ok(!vm.someNumber.isValid(), 'Object is not valid'); - assert.equal(vm.someNumber.error(), 'Please enter a value less than or equal to 30.', - 'Message needs to be formatted correctly'); + assert.ok(el, 'found element'); + assert.ok(!vm.someNumber.isValid(), 'Object is not valid'); + assert.equal(vm.someNumber.error(), 'Please enter a value less than or equal to 30.', + 'Message needs to be formatted correctly'); - done(); - }, 1); + done(); + }, 1); }); QUnit.test('max Attribute of 30 should fail for value of "100"', function(assert) { - var done = assert.async(); - assert.expect(3); + var done = assert.async(); + assert.expect(3); - var vm = { - someNumber: ko.validatedObservable() - }; + var vm = { + someNumber: ko.validatedObservable() + }; - addTestHtml(''); - ko.validation.init({ - parseInputAttributes: true - }, true); - applyTestBindings(vm); + addTestHtml(''); + ko.validation.init({ + parseInputAttributes: true + }, true); + applyTestBindings(vm); - setTimeout(function() { - vm.someNumber('100'); // should fail the min rule + setTimeout(function() { + vm.someNumber('100'); // should fail the min rule - var el = $('#myTestInput'); + var el = $('#myTestInput'); - assert.ok(el, 'found element'); - assert.ok(!vm.someNumber.isValid(), 'Object is not valid'); - assert.equal(vm.someNumber.error(), 'Please enter a value less than or equal to 30.', - 'Message needs to be formatted correctly'); + assert.ok(el, 'found element'); + assert.ok(!vm.someNumber.isValid(), 'Object is not valid'); + assert.equal(vm.someNumber.error(), 'Please enter a value less than or equal to 30.', + 'Message needs to be formatted correctly'); - done(); - }, 1); + done(); + }, 1); }); QUnit.test('max Attribute of 30 should fail for value of "100" with text type', function(assert) { - var done = assert.async(); - assert.expect(3); + var done = assert.async(); + assert.expect(3); - var vm = { - someNumber: ko.validatedObservable() - }; + var vm = { + someNumber: ko.validatedObservable() + }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({parseInputAttributes: true}, true); - applyTestBindings(vm); + ko.validation.init({parseInputAttributes: true}, true); + applyTestBindings(vm); - setTimeout(function() { - vm.someNumber(100); // should fail the min rule + setTimeout(function() { + vm.someNumber(100); // should fail the min rule - var el = $('#myTestInput'); + var el = $('#myTestInput'); - assert.ok(el, 'found element'); - assert.ok(!vm.someNumber.isValid(), 'Object is not valid'); - assert.equal(vm.someNumber.error(), 'Please enter a value less than or equal to 30.', - 'Message needs to be formatted correctly'); + assert.ok(el, 'found element'); + assert.ok(!vm.someNumber.isValid(), 'Object is not valid'); + assert.equal(vm.someNumber.error(), 'Please enter a value less than or equal to 30.', + 'Message needs to be formatted correctly'); - done(); - }, 1); + done(); + }, 1); }); QUnit.test('max Attribute of 30 should pass for value of 5', function(assert) { - var done = assert.async(); - assert.expect(2); + var done = assert.async(); + assert.expect(2); - var vm = { - someNumber: ko.validatedObservable() - }; + var vm = { + someNumber: ko.validatedObservable() + }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({parseInputAttributes: true}, true); - applyTestBindings(vm); + ko.validation.init({parseInputAttributes: true}, true); + applyTestBindings(vm); - setTimeout(function() { - vm.someNumber(5); // should validate the min rule + setTimeout(function() { + vm.someNumber(5); // should validate the min rule - var el = $('#myTestInput'); + var el = $('#myTestInput'); - assert.ok(el, 'found element'); - assert.ok(vm.someNumber.isValid(), 'Object is valid'); + assert.ok(el, 'found element'); + assert.ok(vm.someNumber.isValid(), 'Object is valid'); - done(); - }, 1); + done(); + }, 1); }); QUnit.test('max Attribute of 30 should pass for value of "5"', function(assert) { - var done = assert.async(); - assert.expect(2); + var done = assert.async(); + assert.expect(2); - var vm = { - someNumber: ko.validatedObservable() - }; + var vm = { + someNumber: ko.validatedObservable() + }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({parseInputAttributes: true}, true); - applyTestBindings(vm); + ko.validation.init({parseInputAttributes: true}, true); + applyTestBindings(vm); - setTimeout(function() { - vm.someNumber('5'); // should validate the min rule + setTimeout(function() { + vm.someNumber('5'); // should validate the min rule - var el = $('#myTestInput'); + var el = $('#myTestInput'); - assert.ok(el, 'found element'); - assert.ok(vm.someNumber.isValid(), 'Object is valid'); + assert.ok(el, 'found element'); + assert.ok(vm.someNumber.isValid(), 'Object is valid'); - done(); - }, 1); + done(); + }, 1); }); QUnit.test('max Attribute of 2010-09 should fail for value of 2011-03', function(assert) { - var done = assert.async(); - assert.expect(2); + var done = assert.async(); + assert.expect(2); - var vm = { - someNumber: ko.validatedObservable() - }; + var vm = { + someNumber: ko.validatedObservable() + }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({parseInputAttributes: true}, true); - applyTestBindings(vm); + ko.validation.init({parseInputAttributes: true}, true); + applyTestBindings(vm); - setTimeout(function() { - vm.someNumber('2011-03'); // should fail the max rule + setTimeout(function() { + vm.someNumber('2011-03'); // should fail the max rule - var el = $('#myTestInput'); + var el = $('#myTestInput'); - assert.ok(el, 'found element'); - assert.ok(!vm.someNumber.isValid(), 'Object is not valid'); + assert.ok(el, 'found element'); + assert.ok(!vm.someNumber.isValid(), 'Object is not valid'); - done(); - }, 1); + done(); + }, 1); }); QUnit.test('max Attribute of 2010-09 should succeed for value of 2010-08', function(assert) { - var done = assert.async(); - assert.expect(2); + var done = assert.async(); + assert.expect(2); - var vm = { - someNumber: ko.validatedObservable() - }; + var vm = { + someNumber: ko.validatedObservable() + }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({parseInputAttributes: true}, true); - applyTestBindings(vm); + ko.validation.init({parseInputAttributes: true}, true); + applyTestBindings(vm); - setTimeout(function() { - vm.someNumber('2010-08'); // should succeed the max rule + setTimeout(function() { + vm.someNumber('2010-08'); // should succeed the max rule - var el = $('#myTestInput'); + var el = $('#myTestInput'); - assert.ok(el, 'found element'); - assert.ok(vm.someNumber.isValid(), 'Object is valid'); + assert.ok(el, 'found element'); + assert.ok(vm.someNumber.isValid(), 'Object is valid'); - done(); - }, 1); + done(); + }, 1); }); QUnit.test('min Attribute of 2010-09 should fail for value of 2010-08', function(assert) { - var done = assert.async(); - assert.expect(3); + var done = assert.async(); + assert.expect(3); - var vm = { - someNumber: ko.validatedObservable() - }; + var vm = { + someNumber: ko.validatedObservable() + }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({parseInputAttributes: true}, true); - applyTestBindings(vm); + ko.validation.init({parseInputAttributes: true}, true); + applyTestBindings(vm); - setTimeout(function() { - vm.someNumber('2010-08'); // should fail the min rule + setTimeout(function() { + vm.someNumber('2010-08'); // should fail the min rule - var el = $('#myTestInput'); + var el = $('#myTestInput'); - assert.ok(el, 'found element'); - assert.ok(!vm.someNumber.isValid(), 'Object is valid'); - assert.equal(vm.someNumber.error(), 'Please enter a value greater than or equal to 2010-09.', - 'Message needs to be formatted correctly'); + assert.ok(el, 'found element'); + assert.ok(!vm.someNumber.isValid(), 'Object is valid'); + assert.equal(vm.someNumber.error(), 'Please enter a value greater than or equal to 2010-09.', + 'Message needs to be formatted correctly'); - done(); - }, 1); + done(); + }, 1); }); QUnit.test('min Attribute of 2012-05 should fail for value of 2011-01', function(assert) { - var done = assert.async(); - assert.expect(3); + var done = assert.async(); + assert.expect(3); - var vm = { - someNumber: ko.validatedObservable() - }; + var vm = { + someNumber: ko.validatedObservable() + }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({parseInputAttributes: true}, true); - applyTestBindings(vm); + ko.validation.init({parseInputAttributes: true}, true); + applyTestBindings(vm); - setTimeout(function() { - vm.someNumber('2011-01'); // should fail the min rule + setTimeout(function() { + vm.someNumber('2011-01'); // should fail the min rule - var el = $('#myTestInput'); + var el = $('#myTestInput'); - assert.ok(el, 'found element'); - assert.ok(!vm.someNumber.isValid(), 'Object is valid'); - assert.equal(vm.someNumber.error(), 'Please enter a value greater than or equal to 2012-05.', - 'Message needs to be formatted correctly'); + assert.ok(el, 'found element'); + assert.ok(!vm.someNumber.isValid(), 'Object is valid'); + assert.equal(vm.someNumber.error(), 'Please enter a value greater than or equal to 2012-05.', + 'Message needs to be formatted correctly'); - done(); - }, 1); + done(); + }, 1); }); QUnit.test('min Attribute of 2012-03 should succeed for value of 2013-01', function(assert) { - var done = assert.async(); - assert.expect(2); + var done = assert.async(); + assert.expect(2); - var vm = { - someNumber: ko.validatedObservable() - }; + var vm = { + someNumber: ko.validatedObservable() + }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({parseInputAttributes: true}, true); - applyTestBindings(vm); + ko.validation.init({parseInputAttributes: true}, true); + applyTestBindings(vm); - setTimeout(function() { - vm.someNumber('2013-01'); // should succeed the min rule + setTimeout(function() { + vm.someNumber('2013-01'); // should succeed the min rule - var el = $('#myTestInput'); + var el = $('#myTestInput'); - assert.ok(el, 'found element'); - assert.ok(vm.someNumber.isValid(), 'Object is valid'); + assert.ok(el, 'found element'); + assert.ok(vm.someNumber.isValid(), 'Object is valid'); - done(); - }, 1); + done(); + }, 1); }); QUnit.test('max Attribute of 2010-W09 should fail for value of 2011-W03', function(assert) { - var done = assert.async(); - assert.expect(3); + var done = assert.async(); + assert.expect(3); - var vm = { - someNumber: ko.validatedObservable() - }; + var vm = { + someNumber: ko.validatedObservable() + }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({parseInputAttributes: true}, true); - applyTestBindings(vm); + ko.validation.init({parseInputAttributes: true}, true); + applyTestBindings(vm); - setTimeout(function() { - vm.someNumber('2011-W03'); // should fail the max rule + setTimeout(function() { + vm.someNumber('2011-W03'); // should fail the max rule - var el = $('#myTestInput'); + var el = $('#myTestInput'); - assert.ok(el, 'found element'); - assert.ok(!vm.someNumber.isValid(), 'Object is not valid'); - assert.equal(vm.someNumber.error(), 'Please enter a value less than or equal to 2010-W09.', - 'Message needs to be formatted correctly'); + assert.ok(el, 'found element'); + assert.ok(!vm.someNumber.isValid(), 'Object is not valid'); + assert.equal(vm.someNumber.error(), 'Please enter a value less than or equal to 2010-W09.', + 'Message needs to be formatted correctly'); - done(); - }, 1); + done(); + }, 1); }); QUnit.test('max Attribute of 2010-W09 should succeed for value of 2010-W08', function(assert) { - var done = assert.async(); - assert.expect(2); + var done = assert.async(); + assert.expect(2); - var vm = { - someNumber: ko.validatedObservable() - }; + var vm = { + someNumber: ko.validatedObservable() + }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({parseInputAttributes: true}, true); - applyTestBindings(vm); + ko.validation.init({parseInputAttributes: true}, true); + applyTestBindings(vm); - setTimeout(function() { - vm.someNumber('2010-W08'); // should succeed the max rule + setTimeout(function() { + vm.someNumber('2010-W08'); // should succeed the max rule - var el = $('#myTestInput'); + var el = $('#myTestInput'); - assert.ok(el, 'found element'); - assert.ok(vm.someNumber.isValid(), 'Object is valid'); + assert.ok(el, 'found element'); + assert.ok(vm.someNumber.isValid(), 'Object is valid'); - done(); - }, 1); + done(); + }, 1); }); QUnit.test('min Attribute of 2010-W09 should fail for value of 2010-W08', function(assert) { - var done = assert.async(); - assert.expect(3); + var done = assert.async(); + assert.expect(3); - var vm = { - someNumber: ko.validatedObservable() - }; + var vm = { + someNumber: ko.validatedObservable() + }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({parseInputAttributes: true}, true); - applyTestBindings(vm); + ko.validation.init({parseInputAttributes: true}, true); + applyTestBindings(vm); - setTimeout(function() { - vm.someNumber('2010-W08'); // should fail the min rule + setTimeout(function() { + vm.someNumber('2010-W08'); // should fail the min rule - var el = $('#myTestInput'); + var el = $('#myTestInput'); - assert.ok(el, 'found element'); - assert.ok(!vm.someNumber.isValid(), 'Object is valid'); - assert.equal(vm.someNumber.error(), 'Please enter a value greater than or equal to 2010-W09.', - 'Message needs to be formatted correctly'); + assert.ok(el, 'found element'); + assert.ok(!vm.someNumber.isValid(), 'Object is valid'); + assert.equal(vm.someNumber.error(), 'Please enter a value greater than or equal to 2010-W09.', + 'Message needs to be formatted correctly'); - done(); - }, 1); + done(); + }, 1); }); QUnit.test('min Attribute of 2012-W05 should fail for value of 2011-W01', function(assert) { - var done = assert.async(); - assert.expect(3); + var done = assert.async(); + assert.expect(3); - var vm = { - someNumber: ko.validatedObservable() - }; + var vm = { + someNumber: ko.validatedObservable() + }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({parseInputAttributes: true}, true); - applyTestBindings(vm); + ko.validation.init({parseInputAttributes: true}, true); + applyTestBindings(vm); - setTimeout(function() { - vm.someNumber('2011-W01'); // should fail the min rule + setTimeout(function() { + vm.someNumber('2011-W01'); // should fail the min rule - var el = $('#myTestInput'); + var el = $('#myTestInput'); - assert.ok(el, 'found element'); - assert.ok(!vm.someNumber.isValid(), 'Object is valid'); - assert.equal(vm.someNumber.error(), 'Please enter a value greater than or equal to 2012-W05.', - 'Message needs to be formatted correctly'); + assert.ok(el, 'found element'); + assert.ok(!vm.someNumber.isValid(), 'Object is valid'); + assert.equal(vm.someNumber.error(), 'Please enter a value greater than or equal to 2012-W05.', + 'Message needs to be formatted correctly'); - done(); - }, 1); + done(); + }, 1); }); QUnit.test('min Attribute of 2012-W03 should succeed for value of 2013-W01', function(assert) { - var done = assert.async(); - assert.expect(2); + var done = assert.async(); + assert.expect(2); - var vm = { - someNumber: ko.validatedObservable() - }; + var vm = { + someNumber: ko.validatedObservable() + }; - addTestHtml(''); + addTestHtml(''); - ko.validation.init({parseInputAttributes: true}, true); - applyTestBindings(vm); + ko.validation.init({parseInputAttributes: true}, true); + applyTestBindings(vm); - setTimeout(function() { - vm.someNumber('2013-W01'); // should succeed the min rule + setTimeout(function() { + vm.someNumber('2013-W01'); // should succeed the min rule - var el = $('#myTestInput'); + var el = $('#myTestInput'); - assert.ok(el, 'found element'); - assert.ok(vm.someNumber.isValid(), 'Object is valid'); + assert.ok(el, 'found element'); + assert.ok(vm.someNumber.isValid(), 'Object is valid'); - done(); - }, 1); + done(); + }, 1); }); //#endregion From 2a4d8ed6c927632a340ebe4b995fea9a39116bbf Mon Sep 17 00:00:00 2001 From: Elias Baryshnikov Date: Mon, 14 Mar 2016 01:59:22 +0500 Subject: [PATCH 158/165] improve example for custom rules usage Closes #609 --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b6be5c0e..a67ae5d6 100644 --- a/README.md +++ b/README.md @@ -133,14 +133,14 @@ The validator function takes in the observable's value, and the `params` that yo ```javascript ko.validation.rules['mustEqual'] = { - validator: function (val, otherVal) { - return val === otherVal; + validator: function (val, params) { + return val === params; }, message: 'The field must equal {0}' }; ko.validation.registerExtenders(); -//the value '5' is the second arg ('otherVal') that is passed to the validator +//the value '5' is the second arg ('params') that is passed to the validator var myCustomObj = ko.observable().extend({ mustEqual: 5 }); ``` Learn more about Custom Rules on the [WIKI](https://github.com/Knockout-Contrib/Knockout-Validation/wiki/Custom-Validation-Rules) From 85c222084792a5cd612b527e862882fbc41bce79 Mon Sep 17 00:00:00 2001 From: Hernandes Junio de Assis Date: Tue, 10 May 2016 21:24:19 -0300 Subject: [PATCH 159/165] Fix #617 - isEmptyVal doesn't always return a boolean Closes #620 --- dist/knockout.validation.js | 6 ++++-- dist/knockout.validation.min.js | 2 +- dist/knockout.validation.min.js.map | 2 +- src/utils.js | 5 +++-- 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/dist/knockout.validation.js b/dist/knockout.validation.js index 1fb474de..2351a73e 100644 --- a/dist/knockout.validation.js +++ b/dist/knockout.validation.js @@ -87,7 +87,7 @@ kv.configuration = configuration; return o !== null && typeof o === 'object'; }, isNumber: function(o) { - return !isNaN(o); + return !isNaN(o); }, isObservableArray: function(instance) { return !!instance && @@ -172,6 +172,7 @@ kv.configuration = configuration; if (val === "") { return true; } + return false; }, getOriginalElementTitle: function (element) { var savedOriginalTitle = kv.utils.getAttribute(element, 'data-orig-title'), @@ -196,7 +197,8 @@ kv.configuration = configuration; } } }; -}());;var api = (function () { +}()); +;var api = (function () { var isInitialized = 0, configuration = kv.configuration, diff --git a/dist/knockout.validation.min.js b/dist/knockout.validation.min.js index 6b84cb51..a5b1532c 100644 --- a/dist/knockout.validation.min.js +++ b/dist/knockout.validation.min.js @@ -7,5 +7,5 @@ =============================================================================== */ -!function(e){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?e(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],e):e(ko,ko.validation={})}(function(f,e){if(void 0===f)throw new Error("Knockout is required, please ensure it is loaded before loading this validation plug-in");f.validation=e;var t,i,a,c=f.validation,o=f.utils,p=o.unwrapObservable,n=o.arrayForEach,u=o.extend,r={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0,live:!1},validate:{}},s=u({},r);s.html5Attributes=["required","pattern","min","max","step"],s.html5InputTypes=["email","number","date"],s.reset=function(){u(s,r)},c.configuration=s,c.utils=(t=(new Date).getTime(),i={},a="__ko_validation__",{isArray:function(e){return e.isArray||"[object Array]"===Object.prototype.toString.call(e)},isObject:function(e){return null!==e&&"object"==typeof e},isNumber:function(e){return!isNaN(e)},isObservableArray:function(e){return!!e&&"function"==typeof e.remove&&"function"==typeof e.removeAll&&"function"==typeof e.destroy&&"function"==typeof e.destroyAll&&"function"==typeof e.indexOf&&"function"==typeof e.replace},values:function(e){var t=[];for(var r in e)e.hasOwnProperty(r)&&t.push(e[r]);return t},getValue:function(e){return"function"==typeof e?e():e},hasAttribute:function(e,t){return null!==e.getAttribute(t)},getAttribute:function(e,t){return e.getAttribute(t)},setAttribute:function(e,t,r){return e.setAttribute(t,r)},isValidatable:function(e){return!!(e&&e.rules&&e.isValid&&e.isModified)},insertAfter:function(e,t){e.parentNode.insertBefore(t,e.nextSibling)},newId:function(){return t+=1},getConfigOptions:function(e){return c.utils.contextFor(e)||c.configuration},setDomData:function(e,t){var r=e[a];r||(e[a]=r=c.utils.newId()),i[r]=t},getDomData:function(e){var t=e[a];if(t)return i[t]},contextFor:function(e){switch(e.nodeType){case 1:case 8:var t=c.utils.getDomData(e);if(t)return t;if(e.parentNode)return c.utils.contextFor(e.parentNode)}},isEmptyVal:function(e){return null==e||""===e||void 0},getOriginalElementTitle:function(e){var t=c.utils.getAttribute(e,"data-orig-title"),r=e.title;return c.utils.hasAttribute(e,"data-orig-title")?t:r},async:function(e){window.setImmediate?window.setImmediate(e):window.setTimeout(e,0)},forEach:function(e,t){if(c.utils.isArray(e))return n(e,t);for(var r in e)e.hasOwnProperty(r)&&t(e[r],r)}});var l,d,v,g=(l=0,d=c.configuration,v=c.utils,{init:function(e,t){0s[1]||n[1]===s[1]&&n[2]>=s[2]);case"month":if(a=/^(\d{4})-(\d{2})$/,null===(n=e.match(a)))throw new Error("Invalid value for "+u+" attribute for month input. Should look like '2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min");return!!(s=r.match(a))&&(l?n[1]s[1]||n[1]===s[1]&&n[2]>=s[2]);case"number":case"range":return l?!isNaN(e)&&parseFloat(e)<=parseFloat(r):!isNaN(e)&&parseFloat(e)>=parseFloat(r);default:return l?e<=r:r<=e}}}function h(i,a,n){i.isValidating(!0);function e(e){var t=!1,r="";i.__valid__()&&(e.message?(t=e.isValid,r=e.message):t=e,t||(i.error(c.formatMessage(r||n.message||a.message,p(n.params),i)),i.__valid__(t))),i.isValidating(!1)}c.utils.async(function(){a.validator(i(),void 0===n.params||p(n.params),e)})}u(f.validation,g),c.rules={},c.rules.required={validator:function(e,t){var r;return null==e?!t:("string"==typeof(r=e)&&(r=String.prototype.trim?e.trim():e.replace(/^\s+|\s+$/g,"")),!t||0<(r+"").length)},message:"This field is required."},c.rules.min={validator:y("min"),message:"Please enter a value greater than or equal to {0}."},c.rules.max={validator:y("max"),message:"Please enter a value less than or equal to {0}."},c.rules.minLength={validator:function(e,t){return!!c.utils.isEmptyVal(e)||(c.utils.isNumber(e)?""+e:e).length>=t},message:"Please enter at least {0} characters."},c.rules.maxLength={validator:function(e,t){return!!c.utils.isEmptyVal(e)||(c.utils.isNumber(e)?""+e:e).length<=t},message:"Please enter no more than {0} characters."},c.rules.pattern={validator:function(e,t){return c.utils.isEmptyVal(e)||null!==e.toString().match(t)},message:"Please check this value."},c.rules.step={validator:function(e,t){if(c.utils.isEmptyVal(e)||"any"===t)return!0;var r=100*e%(100*t);return Math.abs(r)<1e-5||Math.abs(1-r)<1e-5},message:"The value must increment by {0}."},c.rules.email={validator:function(e,t){return!t||(c.utils.isEmptyVal(e)||t&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(e))},message:"Please enter a proper email address."},c.rules.date={validator:function(e,t){return!t||(c.utils.isEmptyVal(e)||t&&!/Invalid|NaN/.test(new Date(e)))},message:"Please enter a proper date."},c.rules.dateISO={validator:function(e,t){return!t||(c.utils.isEmptyVal(e)||t&&/^\d{4}[-/](?:0?[1-9]|1[012])[-/](?:0?[1-9]|[12][0-9]|3[01])$/.test(e))},message:"Please enter a proper date."},c.rules.number={validator:function(e,t){return!t||(c.utils.isEmptyVal(e)||t&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(e))},message:"Please enter a number."},c.rules.digit={validator:function(e,t){return!t||(c.utils.isEmptyVal(e)||t&&/^\d+$/.test(e))},message:"Please enter a digit."},c.rules.phoneUS={validator:function(e,t){return!t||(!!c.utils.isEmptyVal(e)||"string"==typeof e&&(e=e.replace(/\s+/g,""),t&&9s[1]||n[1]===s[1]&&n[2]>=s[2]);case"month":if(a=/^(\d{4})-(\d{2})$/,null===(n=e.match(a)))throw new Error("Invalid value for "+u+" attribute for month input. Should look like '2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min");return!!(s=r.match(a))&&(l?n[1]s[1]||n[1]===s[1]&&n[2]>=s[2]);case"number":case"range":return l?!isNaN(e)&&parseFloat(e)<=parseFloat(r):!isNaN(e)&&parseFloat(e)>=parseFloat(r);default:return l?e<=r:r<=e}}}function h(i,a,n){i.isValidating(!0);function e(e){var t=!1,r="";i.__valid__()&&(e.message?(t=e.isValid,r=e.message):t=e,t||(i.error(c.formatMessage(r||n.message||a.message,p(n.params),i)),i.__valid__(t))),i.isValidating(!1)}c.utils.async(function(){a.validator(i(),void 0===n.params||p(n.params),e)})}u(f.validation,g),c.rules={},c.rules.required={validator:function(e,t){var r;return null==e?!t:("string"==typeof(r=e)&&(r=String.prototype.trim?e.trim():e.replace(/^\s+|\s+$/g,"")),!t||0<(r+"").length)},message:"This field is required."},c.rules.min={validator:y("min"),message:"Please enter a value greater than or equal to {0}."},c.rules.max={validator:y("max"),message:"Please enter a value less than or equal to {0}."},c.rules.minLength={validator:function(e,t){return!!c.utils.isEmptyVal(e)||(c.utils.isNumber(e)?""+e:e).length>=t},message:"Please enter at least {0} characters."},c.rules.maxLength={validator:function(e,t){return!!c.utils.isEmptyVal(e)||(c.utils.isNumber(e)?""+e:e).length<=t},message:"Please enter no more than {0} characters."},c.rules.pattern={validator:function(e,t){return c.utils.isEmptyVal(e)||null!==e.toString().match(t)},message:"Please check this value."},c.rules.step={validator:function(e,t){if(c.utils.isEmptyVal(e)||"any"===t)return!0;var r=100*e%(100*t);return Math.abs(r)<1e-5||Math.abs(1-r)<1e-5},message:"The value must increment by {0}."},c.rules.email={validator:function(e,t){return!t||(c.utils.isEmptyVal(e)||t&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(e))},message:"Please enter a proper email address."},c.rules.date={validator:function(e,t){return!t||(c.utils.isEmptyVal(e)||t&&!/Invalid|NaN/.test(new Date(e)))},message:"Please enter a proper date."},c.rules.dateISO={validator:function(e,t){return!t||(c.utils.isEmptyVal(e)||t&&/^\d{4}[-/](?:0?[1-9]|1[012])[-/](?:0?[1-9]|[12][0-9]|3[01])$/.test(e))},message:"Please enter a proper date."},c.rules.number={validator:function(e,t){return!t||(c.utils.isEmptyVal(e)||t&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(e))},message:"Please enter a number."},c.rules.digit={validator:function(e,t){return!t||(c.utils.isEmptyVal(e)||t&&/^\d+$/.test(e))},message:"Please enter a digit."},c.rules.phoneUS={validator:function(e,t){return!t||(!!c.utils.isEmptyVal(e)||"string"==typeof e&&(e=e.replace(/\s+/g,""),t&&9 Date: Tue, 28 Feb 2017 11:34:28 +0100 Subject: [PATCH 160/165] save as a dependency instead when installing via Bower --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a67ae5d6..3a587003 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ License: [MIT](http://www.opensource.org/licenses/mit-license.php) #### Bower ```sh -bower install knockout-validation --save-dev +bower install knockout-validation --save ``` #### NuGet From cad042c368385b73ab06d4a71eaead1400059dee Mon Sep 17 00:00:00 2001 From: harrison314 Date: Sat, 6 Feb 2016 11:12:45 +0100 Subject: [PATCH 161/165] add Slovak - Slovak Republic (sk-SK) localization Closes #605 --- localization/sk-SK.js | 39 +++++++++++++++++ test/locale-tests.js | 1 + test/test-runner-2.3.0.html | 87 +++++++++++++++++++------------------ test/test-runner-3.4.2.html | 3 +- test/test-runner-3.5.0.html | 3 +- 5 files changed, 88 insertions(+), 45 deletions(-) create mode 100644 localization/sk-SK.js diff --git a/localization/sk-SK.js b/localization/sk-SK.js new file mode 100644 index 00000000..6fe7b650 --- /dev/null +++ b/localization/sk-SK.js @@ -0,0 +1,39 @@ +/** + * Localization file for Slovak - Slovak Republic (sk-SK) + */ +(function (factory) { + // Module systems magic dance. + /*global require,ko.validation,define,module*/ + if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') { + // CommonJS or Node + module.exports = factory(require('../')); + } else if (typeof define === 'function' && define['amd']) { + // AMD anonymous module with hard-coded dependency on 'knockout.validation' + define(['knockout.validation'], factory); + } else { + // + - - - + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - + + + + + + + Knockout JS Validation Tests (KnockoutJS v2.3.0)