breeze-client 2.2.2 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +83 -63
- package/adapters/abstract-data-service-adapter.d.ts +120 -0
- package/adapters/abstract-data-service-adapter.js +395 -0
- package/adapters/abstract-data-service-adapter.js.map +1 -0
- package/adapters/adapter-ajax-fetch.d.ts +12 -0
- package/adapters/adapter-ajax-fetch.js +13 -0
- package/adapters/adapter-ajax-fetch.js.map +1 -0
- package/{adapter-ajax-post → adapters}/adapter-ajax-post.d.ts +40 -36
- package/{fesm2022/breeze-client-adapter-ajax-post.mjs → adapters/adapter-ajax-post.js} +80 -82
- package/adapters/adapter-ajax-post.js.map +1 -0
- package/{adapter-ajax-fetch → adapters}/adapter-core.d.ts +4 -4
- package/{fesm2022/breeze-client-adapter-uri-builder-json.mjs → adapters/adapter-core.js} +48 -91
- package/adapters/adapter-core.js.map +1 -0
- package/adapters/adapter-data-service-webapi.d.ts +9 -0
- package/{fesm2022/breeze-client-adapter-data-service-webapi.mjs → adapters/adapter-data-service-webapi.js} +105 -107
- package/adapters/adapter-data-service-webapi.js.map +1 -0
- package/adapters/adapter-model-library-backing-store.d.ts +32 -0
- package/adapters/adapter-model-library-backing-store.js +321 -0
- package/adapters/adapter-model-library-backing-store.js.map +1 -0
- package/adapters/adapter-uri-builder-json.d.ts +11 -0
- package/adapters/adapter-uri-builder-json.js +40 -0
- package/adapters/adapter-uri-builder-json.js.map +1 -0
- package/adapters/http.d.ts +52 -0
- package/adapters/http.js +202 -0
- package/adapters/http.js.map +1 -0
- package/angular/adapter-angular-httpclient.d.ts +21 -0
- package/angular/adapter-angular-httpclient.js +70 -0
- package/angular/adapter-angular-httpclient.js.map +1 -0
- package/breeze.d.ts +215 -0
- package/breeze.js +141 -0
- package/breeze.js.map +1 -0
- package/config/config.d.ts +212 -0
- package/config/config.js +392 -0
- package/config/config.js.map +1 -0
- package/config/configure.d.ts +66 -0
- package/config/configure.js +46 -0
- package/config/configure.js.map +1 -0
- package/config/default-adapters.d.ts +1 -0
- package/config/default-adapters.js +40 -0
- package/config/default-adapters.js.map +1 -0
- package/config/interface-registry.d.ts +191 -0
- package/config/interface-registry.js +5 -0
- package/config/interface-registry.js.map +1 -0
- package/{src → core}/assert-param.d.ts +52 -60
- package/core/assert-param.js +390 -0
- package/core/assert-param.js.map +1 -0
- package/core/core.d.ts +285 -0
- package/core/core.js +772 -0
- package/core/core.js.map +1 -0
- package/core/enum.d.ts +116 -0
- package/core/enum.js +167 -0
- package/core/enum.js.map +1 -0
- package/core/event.d.ts +169 -0
- package/core/event.js +338 -0
- package/core/event.js.map +1 -0
- package/entity/array.d.ts +3 -0
- package/entity/array.js +4 -0
- package/entity/array.js.map +1 -0
- package/entity/complex-array.d.ts +17 -0
- package/entity/complex-array.js +104 -0
- package/entity/complex-array.js.map +1 -0
- package/entity/default-property-interceptor.d.ts +1 -0
- package/entity/default-property-interceptor.js +496 -0
- package/entity/default-property-interceptor.js.map +1 -0
- package/{src → entity}/entity-action.d.ts +36 -42
- package/entity/entity-action.js +45 -0
- package/entity/entity-action.js.map +1 -0
- package/entity/entity-aspect.d.ts +457 -0
- package/entity/entity-aspect.js +1262 -0
- package/entity/entity-aspect.js.map +1 -0
- package/entity/entity-base.d.ts +55 -0
- package/entity/entity-base.js +41 -0
- package/entity/entity-base.js.map +1 -0
- package/entity/entity-group.d.ts +1 -0
- package/entity/entity-group.js +224 -0
- package/entity/entity-group.js.map +1 -0
- package/entity/entity-key.d.ts +95 -0
- package/entity/entity-key.js +189 -0
- package/entity/entity-key.js.map +1 -0
- package/{src → entity}/entity-state.d.ts +112 -84
- package/entity/entity-state.js +135 -0
- package/entity/entity-state.js.map +1 -0
- package/entity/key-generator.d.ts +57 -0
- package/entity/key-generator.js +155 -0
- package/entity/key-generator.js.map +1 -0
- package/entity/observable-array.d.ts +25 -0
- package/entity/observable-array.js +230 -0
- package/entity/observable-array.js.map +1 -0
- package/entity/primitive-array.d.ts +12 -0
- package/entity/primitive-array.js +71 -0
- package/entity/primitive-array.js.map +1 -0
- package/entity/relation-array.d.ts +24 -0
- package/entity/relation-array.js +176 -0
- package/entity/relation-array.js.map +1 -0
- package/entity/unattached-children-map.d.ts +1 -0
- package/entity/unattached-children-map.js +105 -0
- package/entity/unattached-children-map.js.map +1 -0
- package/generate-entity-classes.js +1176 -0
- package/manager/entity-manager.d.ts +801 -0
- package/manager/entity-manager.js +2395 -0
- package/manager/entity-manager.js.map +1 -0
- package/{src → manager}/save-options.d.ts +48 -42
- package/manager/save-options.js +51 -0
- package/manager/save-options.js.map +1 -0
- package/{src → metadata}/data-service.d.ts +229 -184
- package/metadata/data-service.js +246 -0
- package/metadata/data-service.js.map +1 -0
- package/metadata/data-type.d.ts +122 -0
- package/metadata/data-type.js +465 -0
- package/metadata/data-type.js.map +1 -0
- package/metadata/entity-metadata.d.ts +1193 -0
- package/metadata/entity-metadata.js +2502 -0
- package/metadata/entity-metadata.js.map +1 -0
- package/{src → metadata}/local-query-comparison-options.d.ts +65 -59
- package/metadata/local-query-comparison-options.js +69 -0
- package/metadata/local-query-comparison-options.js.map +1 -0
- package/{src → metadata}/naming-convention.d.ts +75 -72
- package/metadata/naming-convention.js +97 -0
- package/metadata/naming-convention.js.map +1 -0
- package/mixins/mixin-get-entity-graph.d.ts +63 -0
- package/{fesm2022/breeze-client-mixin-get-entity-graph.mjs → mixins/mixin-get-entity-graph.js} +331 -253
- package/mixins/mixin-get-entity-graph.js.map +1 -0
- package/mixins/mixin-save-queuing.d.ts +98 -0
- package/{fesm2022/breeze-client-mixin-save-queuing.mjs → mixins/mixin-save-queuing.js} +493 -365
- package/mixins/mixin-save-queuing.js.map +1 -0
- package/package.json +63 -94
- package/query/entity-query.d.ts +521 -0
- package/query/entity-query.js +1149 -0
- package/query/entity-query.js.map +1 -0
- package/{src → query}/mapping-context.d.ts +44 -46
- package/query/mapping-context.js +412 -0
- package/query/mapping-context.js.map +1 -0
- package/query/predicate.d.ts +394 -0
- package/query/predicate.js +1294 -0
- package/query/predicate.js.map +1 -0
- package/query/property-path.d.ts +252 -0
- package/query/property-path.js +2 -0
- package/query/property-path.js.map +1 -0
- package/{src → query}/query-options.d.ts +143 -119
- package/query/query-options.js +180 -0
- package/query/query-options.js.map +1 -0
- package/rxjs/breeze-rxjs.d.ts +72 -0
- package/rxjs/breeze-rxjs.js +117 -0
- package/rxjs/breeze-rxjs.js.map +1 -0
- package/validation/validate.d.ts +583 -0
- package/validation/validate.js +961 -0
- package/validation/validate.js.map +1 -0
- package/{src → validation}/validation-options.d.ts +67 -63
- package/validation/validation-options.js +70 -0
- package/validation/validation-options.js.map +1 -0
- package/adapter-ajax-angularjs/adapter-ajax-angularjs.d.ts +0 -17
- package/adapter-ajax-angularjs/adapter-core.d.ts +0 -4
- package/adapter-ajax-angularjs/index.d.ts +0 -5
- package/adapter-ajax-fetch/adapter-ajax-fetch.d.ts +0 -18
- package/adapter-ajax-fetch/index.d.ts +0 -5
- package/adapter-ajax-httpclient/adapter-ajax-httpclient.d.ts +0 -13
- package/adapter-ajax-httpclient/adapter-core.d.ts +0 -4
- package/adapter-ajax-httpclient/index.d.ts +0 -5
- package/adapter-ajax-jquery/adapter-ajax-jquery.d.ts +0 -15
- package/adapter-ajax-jquery/index.d.ts +0 -5
- package/adapter-ajax-post/index.d.ts +0 -5
- package/adapter-data-service-odata/adapter-core.d.ts +0 -4
- package/adapter-data-service-odata/adapter-data-service-odata.d.ts +0 -17
- package/adapter-data-service-odata/index.d.ts +0 -5
- package/adapter-data-service-webapi/adapter-data-service-webapi.d.ts +0 -15
- package/adapter-data-service-webapi/index.d.ts +0 -5
- package/adapter-model-library-backing-store/adapter-model-library-backing-store.d.ts +0 -10
- package/adapter-model-library-backing-store/index.d.ts +0 -5
- package/adapter-model-library-ko/adapter-model-library-ko.d.ts +0 -10
- package/adapter-model-library-ko/index.d.ts +0 -5
- package/adapter-uri-builder-json/adapter-core.d.ts +0 -4
- package/adapter-uri-builder-json/adapter-uri-builder-json.d.ts +0 -8
- package/adapter-uri-builder-json/index.d.ts +0 -5
- package/adapter-uri-builder-odata/adapter-core.d.ts +0 -4
- package/adapter-uri-builder-odata/adapter-uri-builder-odata.d.ts +0 -8
- package/adapter-uri-builder-odata/index.d.ts +0 -5
- package/esm2022/adapter-ajax-angularjs/adapter-ajax-angularjs.mjs +0 -135
- package/esm2022/adapter-ajax-angularjs/adapter-core.mjs +0 -49
- package/esm2022/adapter-ajax-angularjs/breeze-client-adapter-ajax-angularjs.mjs +0 -5
- package/esm2022/adapter-ajax-fetch/adapter-ajax-fetch.mjs +0 -135
- package/esm2022/adapter-ajax-fetch/adapter-core.mjs +0 -49
- package/esm2022/adapter-ajax-fetch/breeze-client-adapter-ajax-fetch.mjs +0 -5
- package/esm2022/adapter-ajax-httpclient/adapter-ajax-httpclient.mjs +0 -139
- package/esm2022/adapter-ajax-httpclient/adapter-core.mjs +0 -49
- package/esm2022/adapter-ajax-httpclient/breeze-client-adapter-ajax-httpclient.mjs +0 -5
- package/esm2022/adapter-ajax-jquery/adapter-ajax-jquery.mjs +0 -107
- package/esm2022/adapter-ajax-jquery/breeze-client-adapter-ajax-jquery.mjs +0 -5
- package/esm2022/adapter-ajax-post/adapter-ajax-post.mjs +0 -77
- package/esm2022/adapter-ajax-post/breeze-client-adapter-ajax-post.mjs +0 -5
- package/esm2022/adapter-data-service-odata/adapter-core.mjs +0 -49
- package/esm2022/adapter-data-service-odata/adapter-data-service-odata.mjs +0 -461
- package/esm2022/adapter-data-service-odata/breeze-client-adapter-data-service-odata.mjs +0 -5
- package/esm2022/adapter-data-service-webapi/adapter-data-service-webapi.mjs +0 -100
- package/esm2022/adapter-data-service-webapi/breeze-client-adapter-data-service-webapi.mjs +0 -5
- package/esm2022/adapter-model-library-backing-store/adapter-model-library-backing-store.mjs +0 -269
- package/esm2022/adapter-model-library-backing-store/breeze-client-adapter-model-library-backing-store.mjs +0 -5
- package/esm2022/adapter-model-library-ko/adapter-model-library-ko.mjs +0 -241
- package/esm2022/adapter-model-library-ko/breeze-client-adapter-model-library-ko.mjs +0 -5
- package/esm2022/adapter-uri-builder-json/adapter-core.mjs +0 -49
- package/esm2022/adapter-uri-builder-json/adapter-uri-builder-json.mjs +0 -37
- package/esm2022/adapter-uri-builder-json/breeze-client-adapter-uri-builder-json.mjs +0 -5
- package/esm2022/adapter-uri-builder-odata/adapter-core.mjs +0 -49
- package/esm2022/adapter-uri-builder-odata/adapter-uri-builder-odata.mjs +0 -191
- package/esm2022/adapter-uri-builder-odata/breeze-client-adapter-uri-builder-odata.mjs +0 -5
- package/esm2022/breeze-client.mjs +0 -5
- package/esm2022/index.mjs +0 -2
- package/esm2022/mixin-get-entity-graph/breeze-client-mixin-get-entity-graph.mjs +0 -5
- package/esm2022/mixin-get-entity-graph/mixin-get-entity-graph.mjs +0 -269
- package/esm2022/mixin-save-queuing/breeze-client-mixin-save-queuing.mjs +0 -5
- package/esm2022/mixin-save-queuing/mixin-save-queuing.mjs +0 -421
- package/esm2022/src/abstract-data-service-adapter.mjs +0 -325
- package/esm2022/src/array.mjs +0 -4
- package/esm2022/src/assert-param.mjs +0 -330
- package/esm2022/src/breeze.mjs +0 -85
- package/esm2022/src/complex-array.mjs +0 -117
- package/esm2022/src/config.mjs +0 -232
- package/esm2022/src/core.mjs +0 -712
- package/esm2022/src/csdl-metadata-parser.mjs +0 -385
- package/esm2022/src/data-service.mjs +0 -221
- package/esm2022/src/data-type.mjs +0 -510
- package/esm2022/src/default-property-interceptor.mjs +0 -460
- package/esm2022/src/entity-action.mjs +0 -45
- package/esm2022/src/entity-aspect.mjs +0 -897
- package/esm2022/src/entity-group.mjs +0 -192
- package/esm2022/src/entity-key.mjs +0 -125
- package/esm2022/src/entity-manager.mjs +0 -2163
- package/esm2022/src/entity-metadata.mjs +0 -2242
- package/esm2022/src/entity-query.mjs +0 -1024
- package/esm2022/src/entity-state.mjs +0 -107
- package/esm2022/src/enum.mjs +0 -143
- package/esm2022/src/event.mjs +0 -264
- package/esm2022/src/interface-registry.mjs +0 -39
- package/esm2022/src/key-generator.mjs +0 -110
- package/esm2022/src/local-query-comparison-options.mjs +0 -65
- package/esm2022/src/mapping-context.mjs +0 -411
- package/esm2022/src/naming-convention.mjs +0 -92
- package/esm2022/src/observable-array.mjs +0 -183
- package/esm2022/src/predicate.mjs +0 -1259
- package/esm2022/src/primitive-array.mjs +0 -85
- package/esm2022/src/query-options.mjs +0 -152
- package/esm2022/src/relation-array.mjs +0 -173
- package/esm2022/src/save-options.mjs +0 -41
- package/esm2022/src/unattached-children-map.mjs +0 -56
- package/esm2022/src/validate.mjs +0 -995
- package/esm2022/src/validation-options.mjs +0 -64
- package/fesm2022/breeze-client-adapter-ajax-angularjs.mjs +0 -190
- package/fesm2022/breeze-client-adapter-ajax-angularjs.mjs.map +0 -1
- package/fesm2022/breeze-client-adapter-ajax-fetch.mjs +0 -190
- package/fesm2022/breeze-client-adapter-ajax-fetch.mjs.map +0 -1
- package/fesm2022/breeze-client-adapter-ajax-httpclient.mjs +0 -194
- package/fesm2022/breeze-client-adapter-ajax-httpclient.mjs.map +0 -1
- package/fesm2022/breeze-client-adapter-ajax-jquery.mjs +0 -114
- package/fesm2022/breeze-client-adapter-ajax-jquery.mjs.map +0 -1
- package/fesm2022/breeze-client-adapter-ajax-post.mjs.map +0 -1
- package/fesm2022/breeze-client-adapter-data-service-odata.mjs +0 -516
- package/fesm2022/breeze-client-adapter-data-service-odata.mjs.map +0 -1
- package/fesm2022/breeze-client-adapter-data-service-webapi.mjs.map +0 -1
- package/fesm2022/breeze-client-adapter-model-library-backing-store.mjs +0 -276
- package/fesm2022/breeze-client-adapter-model-library-backing-store.mjs.map +0 -1
- package/fesm2022/breeze-client-adapter-model-library-ko.mjs +0 -248
- package/fesm2022/breeze-client-adapter-model-library-ko.mjs.map +0 -1
- package/fesm2022/breeze-client-adapter-uri-builder-json.mjs.map +0 -1
- package/fesm2022/breeze-client-adapter-uri-builder-odata.mjs +0 -246
- package/fesm2022/breeze-client-adapter-uri-builder-odata.mjs.map +0 -1
- package/fesm2022/breeze-client-mixin-get-entity-graph.mjs.map +0 -1
- package/fesm2022/breeze-client-mixin-save-queuing.mjs.map +0 -1
- package/fesm2022/breeze-client.mjs +0 -14144
- package/fesm2022/breeze-client.mjs.map +0 -1
- package/index.d.ts +0 -1
- package/mixin-get-entity-graph/index.d.ts +0 -5
- package/mixin-get-entity-graph/mixin-get-entity-graph.d.ts +0 -31
- package/mixin-save-queuing/index.d.ts +0 -5
- package/mixin-save-queuing/mixin-save-queuing.d.ts +0 -32
- package/src/abstract-data-service-adapter.d.ts +0 -84
- package/src/array.d.ts +0 -3
- package/src/breeze.d.ts +0 -139
- package/src/complex-array.d.ts +0 -13
- package/src/config.d.ts +0 -104
- package/src/core.d.ts +0 -164
- package/src/csdl-metadata-parser.d.ts +0 -7
- package/src/data-type.d.ts +0 -89
- package/src/default-property-interceptor.d.ts +0 -4
- package/src/entity-aspect.d.ts +0 -332
- package/src/entity-group.d.ts +0 -28
- package/src/entity-key.d.ts +0 -77
- package/src/entity-manager.d.ts +0 -680
- package/src/entity-metadata.d.ts +0 -988
- package/src/entity-query.d.ts +0 -444
- package/src/enum.d.ts +0 -100
- package/src/event.d.ts +0 -142
- package/src/interface-registry.d.ts +0 -150
- package/src/key-generator.d.ts +0 -12
- package/src/observable-array.d.ts +0 -52
- package/src/predicate.d.ts +0 -376
- package/src/primitive-array.d.ts +0 -7
- package/src/relation-array.d.ts +0 -18
- package/src/unattached-children-map.d.ts +0 -19
- package/src/validate.d.ts +0 -650
|
@@ -0,0 +1,961 @@
|
|
|
1
|
+
import { core } from '../core/core.js';
|
|
2
|
+
import { assertParam } from '../core/assert-param.js';
|
|
3
|
+
import { config } from '../config/config.js';
|
|
4
|
+
export const INT16_MIN = -32768;
|
|
5
|
+
export const INT16_MAX = 32767;
|
|
6
|
+
export const INT32_MIN = -2147483648;
|
|
7
|
+
export const INT32_MAX = 2147483647;
|
|
8
|
+
export const BYTE_MIN = 0;
|
|
9
|
+
export const BYTE_MAX = 255;
|
|
10
|
+
/** An `async` function - which Breeze can recognize before calling it, unlike one that merely returns a promise. */
|
|
11
|
+
function isAsyncFunction(fn) {
|
|
12
|
+
return Object.prototype.toString.call(fn) === '[object AsyncFunction]';
|
|
13
|
+
}
|
|
14
|
+
function isThenable(value) {
|
|
15
|
+
return value != null && typeof value.then === 'function';
|
|
16
|
+
}
|
|
17
|
+
// add common props and methods for every validator 'context' here.
|
|
18
|
+
let rootContext = {
|
|
19
|
+
displayName: function (context) {
|
|
20
|
+
if (context.property) {
|
|
21
|
+
return context.property.resolveProperty("displayName") || context.propertyName || context.property.name;
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
return "Value";
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
Instances of the Validator class provide the logic to validate another object and provide a description of any errors
|
|
30
|
+
encountered during the validation process. They are typically associated with a 'validators' property on the following types: {@link EntityType},
|
|
31
|
+
{@link DataProperty} or {@link NavigationProperty}.
|
|
32
|
+
|
|
33
|
+
Property-level validators normally arrive with the metadata. The Breeze server sends a
|
|
34
|
+
`validators` array for each data property - for example `required` for a non-nullable
|
|
35
|
+
property, `maxLength` for a string with a maximum length, and a data-type validator such as
|
|
36
|
+
`int32` or `date`. They are not inferred on the client, so metadata written by hand has
|
|
37
|
+
none unless you add them.
|
|
38
|
+
|
|
39
|
+
To write your own, construct one with a name, a validation function and a context. Several
|
|
40
|
+
basic "Validator" construction methods are also provided as static methods to this class. These methods
|
|
41
|
+
provide a simpler syntax for creating basic validations.
|
|
42
|
+
|
|
43
|
+
Many of these stock validators are inspired by and implemented to conform to the validators defined at
|
|
44
|
+
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx
|
|
45
|
+
|
|
46
|
+
Sometimes a custom validator will be required.
|
|
47
|
+
@example
|
|
48
|
+
Most validators will be 'property' level validators, like this.
|
|
49
|
+
@example
|
|
50
|
+
// v in this function is the value to be validated, in this case a "country" string.
|
|
51
|
+
const valFn = (v: string | null) => v == null || v.startsWith("US");
|
|
52
|
+
const countryValidator = new Validator("countryIsUS", valFn, {
|
|
53
|
+
displayName: "Country",
|
|
54
|
+
messageTemplate: "'%displayName%' must start with 'US'"
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
// Now plug it into Breeze.
|
|
58
|
+
// Assume em1 is a preexisting EntityManager.
|
|
59
|
+
const custType = em1.metadataStore.getAsEntityType("Customer");
|
|
60
|
+
const countryProp = custType.getProperty("country");
|
|
61
|
+
// Note that validator is added to a 'DataProperty' validators collection.
|
|
62
|
+
countryProp.validators.push(countryValidator);
|
|
63
|
+
Entity level validators are also possible
|
|
64
|
+
@example
|
|
65
|
+
function isValidZipCode(value: string) {
|
|
66
|
+
const re = /^\d{5}([\-]\d{4})?$/;
|
|
67
|
+
return re.test(value);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// the value in this case will be a Customer entity
|
|
71
|
+
const valFn = (cust: Customer) => {
|
|
72
|
+
// This validator only validates US Zip Codes.
|
|
73
|
+
if (cust.country === "USA") {
|
|
74
|
+
return isValidZipCode(cust.postalCode);
|
|
75
|
+
}
|
|
76
|
+
return true;
|
|
77
|
+
};
|
|
78
|
+
const zipCodeValidator = new Validator("zipCodeValidator", valFn,
|
|
79
|
+
{ messageTemplate: "For the US, this is not a valid PostalCode" });
|
|
80
|
+
|
|
81
|
+
// Now plug it into Breeze.
|
|
82
|
+
// Assume em1 is a preexisting EntityManager.
|
|
83
|
+
const custType = em1.metadataStore.getAsEntityType("Customer");
|
|
84
|
+
// Note that validator is added to an 'EntityType' validators collection.
|
|
85
|
+
custType.validators.push(zipCodeValidator);
|
|
86
|
+
What is commonly needed is a way of creating a parameterized function that will itself
|
|
87
|
+
return a new Validator. This requires the use of a 'context' object.
|
|
88
|
+
@example
|
|
89
|
+
// create a function that will take in a config object
|
|
90
|
+
// and will return a validator
|
|
91
|
+
const numericRangeValidator = (context: { min?: number, max?: number }) => {
|
|
92
|
+
const valFn = (v: any, ctx: ValidationMessageContext) => {
|
|
93
|
+
if (v == null) return true;
|
|
94
|
+
if (typeof v !== "number") return false;
|
|
95
|
+
if (ctx.min != null && v < ctx.min) return false;
|
|
96
|
+
if (ctx.max != null && v > ctx.max) return false;
|
|
97
|
+
return true;
|
|
98
|
+
};
|
|
99
|
+
// The last parameter below is the 'context' object that will be passed into the 'ctx' parameter above
|
|
100
|
+
// when this validator executes. Several other properties, such as displayName will get added to this object as well.
|
|
101
|
+
return new Validator("numericRange", valFn, {
|
|
102
|
+
messageTemplate: "'%displayName%' must be a number between the values of %min% and %max%",
|
|
103
|
+
min: context.min,
|
|
104
|
+
max: context.max
|
|
105
|
+
});
|
|
106
|
+
};
|
|
107
|
+
// Assume that freightProperty is a DataEntityProperty that describes numeric values.
|
|
108
|
+
// register the validator
|
|
109
|
+
freightProperty.validators.push(numericRangeValidator({ min: 100, max: 500 }));
|
|
110
|
+
|
|
111
|
+
Breeze substitutes context values and functions for the tokens in the messageTemplate when preparing the runtime error message;
|
|
112
|
+
'displayName' is a pre-defined context function that is always available.
|
|
113
|
+
|
|
114
|
+
Please note that Breeze substitutes the empty string for falsey parameters. That usually works in your favor.
|
|
115
|
+
Sometimes it doesn't as when the 'min' value is zero in which case the message text would have a hole
|
|
116
|
+
where the 'min' value goes, saying: "... an integer between the values of and ...". That is not what you want.
|
|
117
|
+
|
|
118
|
+
To avoid this effect, you may can bake certain of the context values into the 'messageTemplate' itself
|
|
119
|
+
as shown in this revision to the pertinent part of the previous example:
|
|
120
|
+
@example
|
|
121
|
+
// ... as before
|
|
122
|
+
// ... but bake the min/max values into the message template.
|
|
123
|
+
const template = core.formatString(
|
|
124
|
+
"'%displayName%' must be a number between the values of %1 and %2",
|
|
125
|
+
context.min, context.max);
|
|
126
|
+
return new Validator("numericRange", valFn, {
|
|
127
|
+
messageTemplate: template,
|
|
128
|
+
min: context.min,
|
|
129
|
+
max: context.max
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
@param name {String} The name of this validator.
|
|
133
|
+
@param validatorFn {Function} A function to perform validation.
|
|
134
|
+
|
|
135
|
+
validatorFn(value, context)
|
|
136
|
+
@param validatorFn.value {Object} Value to be validated
|
|
137
|
+
@param validatorFn.context {Object} The same context object passed into the constructor with the following additional properties if not
|
|
138
|
+
otherwise specified.
|
|
139
|
+
@param validatorFn.context.value {Object} The value being validated.
|
|
140
|
+
@param validatorFn.context.name {String} The name of the validator being executed.
|
|
141
|
+
@param validatorFn.context.displayName {String} This will be either the value of the property's 'displayName' property or
|
|
142
|
+
the value of its 'name' property or the string 'Value'
|
|
143
|
+
@param validatorFn.context.messageTemplate {String} This will either be the value of Validator.messageTemplates[ {this validators name}] or null. Validator.messageTemplates
|
|
144
|
+
is an object that is keyed by validator name and that can be added to in order to 'register' your own message for a given validator.
|
|
145
|
+
The following property can also be specified for any validator to force a specific errorMessage string
|
|
146
|
+
@param [validatorFn.context.message] {String} If this property is set it will be used instead of the 'messageTemplate' property when an
|
|
147
|
+
error message is generated.
|
|
148
|
+
|
|
149
|
+
@param [context] {Object} A free form object whose properties will made available during the validation and error message creation process.
|
|
150
|
+
This object will be passed into the Validator's validation function whenever 'validate' is called. See above for a description
|
|
151
|
+
of additional properties that will be automatically added to this object if not otherwise specified.
|
|
152
|
+
*/
|
|
153
|
+
export class Validator {
|
|
154
|
+
/** Creates a validator. See the class description for examples.
|
|
155
|
+
@param name - The validator's name. Also the default `key` of the errors it produces.
|
|
156
|
+
@param valFn - The function that validates: called with the value (or, for an entity-level
|
|
157
|
+
validator, the entity) and the context, it returns whether the value is valid.
|
|
158
|
+
@param context - Settings for the validator and its messages, such as `displayName` and
|
|
159
|
+
`messageTemplate`. They are available to `valFn` and to the error message template.
|
|
160
|
+
*/
|
|
161
|
+
constructor(name, valFn, context) {
|
|
162
|
+
// _baseContext is what will get serialized
|
|
163
|
+
this._baseContext = context || {};
|
|
164
|
+
this._baseContext.name = name;
|
|
165
|
+
context = core.extend(Object.create(rootContext), this._baseContext);
|
|
166
|
+
context.messageTemplate = context.messageTemplate || Validator.messageTemplates[name];
|
|
167
|
+
this.name = name;
|
|
168
|
+
this.valFn = valFn;
|
|
169
|
+
this.context = context;
|
|
170
|
+
this.isAsync = isAsyncFunction(valFn) || !!context.isAsync;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
Run this validator against the specified value. This method will usually be called internally either
|
|
174
|
+
automatically by an property change, entity attach, query or save operation, or manually as a result of
|
|
175
|
+
a validateEntity call on the EntityAspect. The resulting ValidationResults are available via the
|
|
176
|
+
EntityAspect.getValidationErrors method.
|
|
177
|
+
|
|
178
|
+
However, you can also call a validator directly either for testing purposes or some other reason if needed.
|
|
179
|
+
@example
|
|
180
|
+
// using one of the predefined validators
|
|
181
|
+
const validator = Validator.maxLength({ maxLength: 5, displayName: "City" });
|
|
182
|
+
// null, because "asdf".length <= 5
|
|
183
|
+
const noError = validator.validate("asdf");
|
|
184
|
+
const result = validator.validate("adasdfasdf");
|
|
185
|
+
// extract all of the properties of the 'result'
|
|
186
|
+
const errMsg = result.errorMessage;
|
|
187
|
+
const context = result.context;
|
|
188
|
+
const sameValidator = result.validator;
|
|
189
|
+
@param value {Object} Value to validate
|
|
190
|
+
@param additionalContext {Object} Any additional contextual information that the Validator
|
|
191
|
+
can make use of.
|
|
192
|
+
@returns {ValidationError|null} A ValidationError if validation fails, null otherwise
|
|
193
|
+
*/
|
|
194
|
+
validate(value, additionalContext) {
|
|
195
|
+
if (this.isAsync) {
|
|
196
|
+
throw new Error("'" + this.name + "' is an async validator: call validateAsync(), which returns a promise, rather than validate().");
|
|
197
|
+
}
|
|
198
|
+
let currentContext; // { value?: Object };
|
|
199
|
+
if (additionalContext) {
|
|
200
|
+
currentContext = core.extend(Object.create(this.context), additionalContext);
|
|
201
|
+
}
|
|
202
|
+
else {
|
|
203
|
+
currentContext = this.context;
|
|
204
|
+
}
|
|
205
|
+
this.currentContext = currentContext;
|
|
206
|
+
try {
|
|
207
|
+
const result = this.valFn(value, currentContext);
|
|
208
|
+
if (isThenable(result)) {
|
|
209
|
+
// A promise is truthy, so this validator would have passed every value. It is async
|
|
210
|
+
// without saying so: treat it as async from now on, and ignore this answer.
|
|
211
|
+
this.isAsync = true;
|
|
212
|
+
result.then(undefined, () => { });
|
|
213
|
+
console.warn("Breeze: validator '" + this.name + "' returned a promise, so it is async. Declare its function " +
|
|
214
|
+
"'async', or pass { isAsync: true } in its context, so that it is only run where the answer can be awaited.");
|
|
215
|
+
this.currentContext = this.context;
|
|
216
|
+
return null;
|
|
217
|
+
}
|
|
218
|
+
if (result) {
|
|
219
|
+
// Drop the per-call context on success. It names the entity being validated, and a
|
|
220
|
+
// Validator lives on a DataProperty, so on an EntityType, so on the MetadataStore -
|
|
221
|
+
// the longest-lived object there is, and shared between managers. Holding it pins that
|
|
222
|
+
// entity, and everything its navigation properties reach, for the life of the store.
|
|
223
|
+
// Nothing asks for a message after a validation that passed; `this.context` keeps
|
|
224
|
+
// getMessage() answering, without naming a subject.
|
|
225
|
+
this.currentContext = this.context;
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
else {
|
|
229
|
+
currentContext.value = value;
|
|
230
|
+
return new ValidationError(this, currentContext, this._formatMessage(currentContext));
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
catch (e) {
|
|
234
|
+
return new ValidationError(this, currentContext, "Exception occured while executing this validator: " + this.name);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
Runs this validator, sync or async, and resolves with a {@link ValidationError} if the value is
|
|
239
|
+
invalid, or null. Each call has a context of its own, so calls may overlap; unlike
|
|
240
|
+
{@link Validator.validate}, it does not set {@link Validator.currentContext}.
|
|
241
|
+
```ts
|
|
242
|
+
const ve = await Validator.maxLength({ maxLength: 5 }).validateAsync("adasdfasdf");
|
|
243
|
+
```
|
|
244
|
+
A function that throws or rejects gives an error, as it does in `validate`.
|
|
245
|
+
@param value - The value to validate.
|
|
246
|
+
@param additionalContext - Anything else the validator can use, such as the entity and property.
|
|
247
|
+
*/
|
|
248
|
+
async validateAsync(value, additionalContext) {
|
|
249
|
+
const context = (additionalContext
|
|
250
|
+
? core.extend(Object.create(this.context), additionalContext)
|
|
251
|
+
: Object.create(this.context));
|
|
252
|
+
try {
|
|
253
|
+
if (await this.valFn(value, context))
|
|
254
|
+
return null;
|
|
255
|
+
context.value = value;
|
|
256
|
+
return new ValidationError(this, context, this._formatMessage(context));
|
|
257
|
+
}
|
|
258
|
+
catch (e) {
|
|
259
|
+
return new ValidationError(this, context, "Exception occured while executing this validator: " + this.name);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
// context.value is not avail unless validate was called first.
|
|
263
|
+
/**
|
|
264
|
+
Returns the message generated by the most recent execution of this Validator.
|
|
265
|
+
@example
|
|
266
|
+
const v0 = Validator.maxLength({ maxLength: 5, displayName: "City" });
|
|
267
|
+
v0.validate("adasdfasdf");
|
|
268
|
+
const errMessage = v0.getMessage();
|
|
269
|
+
@returns {String}
|
|
270
|
+
*/
|
|
271
|
+
getMessage() {
|
|
272
|
+
return this._formatMessage(this.currentContext);
|
|
273
|
+
}
|
|
274
|
+
/** @hidden @internal */
|
|
275
|
+
_formatMessage(context) {
|
|
276
|
+
try {
|
|
277
|
+
let message = context.message;
|
|
278
|
+
if (message) {
|
|
279
|
+
if (typeof (message) === "function") {
|
|
280
|
+
return message(context);
|
|
281
|
+
}
|
|
282
|
+
else {
|
|
283
|
+
return message;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
else if (context.messageTemplate) {
|
|
287
|
+
return formatTemplate(context.messageTemplate, context);
|
|
288
|
+
}
|
|
289
|
+
else {
|
|
290
|
+
return "invalid value: " + (this.name || "{unnamed validator}");
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
catch (e) {
|
|
294
|
+
return "Unable to format error message" + e.toString();
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
Returns the serializable form of this validator: its `name` plus the context it was created with,
|
|
299
|
+
such as `{ name: "maxLength", maxLength: 50 }`. Breeze uses it when it exports metadata;
|
|
300
|
+
{@link Validator.fromJSON} reads it back through the factory registered under that name.
|
|
301
|
+
*/
|
|
302
|
+
toJSON() {
|
|
303
|
+
return this._baseContext;
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
Creates a validator instance from a JSON object or an array of instances from an array of JSON objects.
|
|
307
|
+
@param json {Object} JSON object that represents the serialized version of a validator.
|
|
308
|
+
*/
|
|
309
|
+
static fromJSON(json) {
|
|
310
|
+
if (Array.isArray(json)) {
|
|
311
|
+
return json.map(function (js) {
|
|
312
|
+
return Validator.fromJSON(js);
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
if (json instanceof Validator) {
|
|
316
|
+
return json;
|
|
317
|
+
}
|
|
318
|
+
let validatorName = "Validator." + json.name;
|
|
319
|
+
let fn = config.getRegisteredFunction(validatorName);
|
|
320
|
+
if (!fn) {
|
|
321
|
+
throw new Error("Unable to locate a validator named:" + json.name);
|
|
322
|
+
}
|
|
323
|
+
return fn(json);
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
Register a validator instance so that any deserialized metadata can reference it.
|
|
327
|
+
@param validator {Validator} Validator to register.
|
|
328
|
+
*/
|
|
329
|
+
static register(validator) {
|
|
330
|
+
config.registerFunction(function () {
|
|
331
|
+
return validator;
|
|
332
|
+
}, "Validator." + validator.name);
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
Register a validator factory so that any deserialized metadata can reference it.
|
|
336
|
+
@param validatorFactory {Function} A function that optionally takes a context property and returns a Validator instance.
|
|
337
|
+
@param name {String} The name of the validator.
|
|
338
|
+
*/
|
|
339
|
+
static registerFactory(validatorFactory, name) {
|
|
340
|
+
config.registerFunction(validatorFactory, "Validator." + name);
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
Map of standard error message templates keyed by validator name.
|
|
344
|
+
You can add to or modify this object to customize the template used for any validation error message.
|
|
345
|
+
@example
|
|
346
|
+
// v in this function is the value to be validated, in this case a "country" string.
|
|
347
|
+
const valFn = (v: string | null) => v == null || v.startsWith("US");
|
|
348
|
+
const countryValidator = new Validator("countryIsUS", valFn, { displayName: "Country" });
|
|
349
|
+
Validator.messageTemplates.countryIsUS = "'%displayName%' must start with 'US'";
|
|
350
|
+
// This will have a similar effect to this
|
|
351
|
+
const countryValidator2 = new Validator("countryIsUS", valFn, {
|
|
352
|
+
displayName: "Country",
|
|
353
|
+
messageTemplate: "'%displayName%' must start with 'US'"
|
|
354
|
+
});
|
|
355
|
+
@property messageTemplates {Object}
|
|
356
|
+
*/
|
|
357
|
+
static messageTemplates = {
|
|
358
|
+
bool: "'%displayName%' must be a 'true' or 'false' value",
|
|
359
|
+
creditCard: "The %displayName% is not a valid credit card number",
|
|
360
|
+
date: "'%displayName%' must be a date",
|
|
361
|
+
duration: "'%displayName%' must be a ISO8601 duration string, such as 'P3H24M60S'",
|
|
362
|
+
emailAddress: "The %displayName% '%value%' is not a valid email address",
|
|
363
|
+
guid: "'%displayName%' must be a GUID",
|
|
364
|
+
integer: "'%displayName%' must be an integer",
|
|
365
|
+
integerRange: "'%displayName%' must be an integer between the values of %minValue% and %maxValue%",
|
|
366
|
+
maxLength: "'%displayName%' must be a string with %maxLength% characters or less",
|
|
367
|
+
number: "'%displayName%' must be a number",
|
|
368
|
+
phone: "The %displayName% '%value%' is not a valid phone number",
|
|
369
|
+
regularExpression: "The %displayName% '%value%' does not match '%expression%'",
|
|
370
|
+
required: "'%displayName%' is required",
|
|
371
|
+
string: "'%displayName%' must be a string",
|
|
372
|
+
stringLength: "'%displayName%' must be a string with between %minLength% and %maxLength% characters",
|
|
373
|
+
url: "The %displayName% '%value%' is not a valid url"
|
|
374
|
+
};
|
|
375
|
+
/**
|
|
376
|
+
Returns a standard 'required value' Validator
|
|
377
|
+
@example
|
|
378
|
+
// Assume em1 is a preexisting EntityManager.
|
|
379
|
+
const custType = em1.metadataStore.getAsEntityType("Customer");
|
|
380
|
+
const regionProperty = custType.getProperty("region");
|
|
381
|
+
// Makes "region" on Customer a required property.
|
|
382
|
+
regionProperty.validators.push(Validator.required());
|
|
383
|
+
// or to allow empty strings
|
|
384
|
+
regionProperty.validators.push(Validator.required({ allowEmptyStrings: true }));
|
|
385
|
+
@param context - An object with `allowEmptyStrings` (boolean) - If this parameter is omitted or false then empty strings do NOT pass validation.
|
|
386
|
+
@returns {Validator} A new Validator
|
|
387
|
+
*/
|
|
388
|
+
static required = function (context) {
|
|
389
|
+
let valFn = function (v, ctx) {
|
|
390
|
+
if (typeof v === "string") {
|
|
391
|
+
if (ctx && ctx.allowEmptyStrings)
|
|
392
|
+
return true;
|
|
393
|
+
return v.length > 0;
|
|
394
|
+
}
|
|
395
|
+
else {
|
|
396
|
+
return v != null;
|
|
397
|
+
}
|
|
398
|
+
};
|
|
399
|
+
return new Validator("required", valFn, context);
|
|
400
|
+
};
|
|
401
|
+
/**
|
|
402
|
+
Returns a standard maximum string length Validator; the maximum length must be specified
|
|
403
|
+
@example
|
|
404
|
+
// Assume em1 is a preexisting EntityManager.
|
|
405
|
+
const custType = em1.metadataStore.getAsEntityType("Customer");
|
|
406
|
+
const regionProperty = custType.getProperty("region");
|
|
407
|
+
// Validates that the value of the region property on Customer will be less than or equal to 5 characters.
|
|
408
|
+
regionProperty.validators.push(Validator.maxLength({ maxLength: 5 }));
|
|
409
|
+
@param context - An object with `maxLength` (number).
|
|
410
|
+
@returns {Validator} A new Validator
|
|
411
|
+
*/
|
|
412
|
+
static maxLength = function (context) {
|
|
413
|
+
let valFn = function (v, ctx) {
|
|
414
|
+
if (v == null)
|
|
415
|
+
return true;
|
|
416
|
+
if (typeof (v) !== "string")
|
|
417
|
+
return false;
|
|
418
|
+
return v.length <= ctx.maxLength;
|
|
419
|
+
};
|
|
420
|
+
return new Validator("maxLength", valFn, context);
|
|
421
|
+
};
|
|
422
|
+
/**
|
|
423
|
+
Returns a standard string length Validator; both minimum and maximum lengths must be specified.
|
|
424
|
+
@example
|
|
425
|
+
// Assume em1 is a preexisting EntityManager.
|
|
426
|
+
const custType = em1.metadataStore.getAsEntityType("Customer");
|
|
427
|
+
const regionProperty = custType.getProperty("region");
|
|
428
|
+
// Validates that the value of the region property on Customer will be
|
|
429
|
+
// between 2 and 5 characters
|
|
430
|
+
regionProperty.validators.push(Validator.stringLength({ minLength: 2, maxLength: 5 }));
|
|
431
|
+
@param context - An object with `maxLength` (number); `minLength` (number).
|
|
432
|
+
@returns {Validator} A new Validator
|
|
433
|
+
*/
|
|
434
|
+
static stringLength = function (context) {
|
|
435
|
+
let valFn = function (v, ctx) {
|
|
436
|
+
if (v == null)
|
|
437
|
+
return true;
|
|
438
|
+
if (typeof (v) !== "string")
|
|
439
|
+
return false;
|
|
440
|
+
if (ctx.minLength != null && v.length < ctx.minLength)
|
|
441
|
+
return false;
|
|
442
|
+
if (ctx.maxLength != null && v.length > ctx.maxLength)
|
|
443
|
+
return false;
|
|
444
|
+
return true;
|
|
445
|
+
};
|
|
446
|
+
return new Validator("stringLength", valFn, context);
|
|
447
|
+
};
|
|
448
|
+
/**
|
|
449
|
+
Returns a standard string dataType Validator.
|
|
450
|
+
@example
|
|
451
|
+
// Assume em1 is a preexisting EntityManager.
|
|
452
|
+
const custType = em1.metadataStore.getAsEntityType("Customer");
|
|
453
|
+
const regionProperty = custType.getProperty("region");
|
|
454
|
+
// Validates that the value of the region property on Customer is a string.
|
|
455
|
+
regionProperty.validators.push(Validator.string());
|
|
456
|
+
@returns {Validator} A new Validator
|
|
457
|
+
*/
|
|
458
|
+
static string = function () {
|
|
459
|
+
let valFn = function (v) {
|
|
460
|
+
if (v == null)
|
|
461
|
+
return true;
|
|
462
|
+
return (typeof v === "string");
|
|
463
|
+
};
|
|
464
|
+
return new Validator("string", valFn);
|
|
465
|
+
};
|
|
466
|
+
/**
|
|
467
|
+
Returns a Guid data type Validator.
|
|
468
|
+
@example
|
|
469
|
+
// Assume em1 is a preexisting EntityManager.
|
|
470
|
+
const custType = em1.metadataStore.getAsEntityType("Customer");
|
|
471
|
+
const customerIdProperty = custType.getProperty("customerID");
|
|
472
|
+
// Validates that the value of the customerID property on Customer is a Guid.
|
|
473
|
+
customerIdProperty.validators.push(Validator.guid());
|
|
474
|
+
@returns {Validator} A new Validator
|
|
475
|
+
*/
|
|
476
|
+
static guid = function () {
|
|
477
|
+
let valFn = function (v) {
|
|
478
|
+
if (v == null)
|
|
479
|
+
return true;
|
|
480
|
+
return core.isGuid(v);
|
|
481
|
+
};
|
|
482
|
+
return new Validator("guid", valFn);
|
|
483
|
+
};
|
|
484
|
+
/**
|
|
485
|
+
Returns a ISO 8601 duration string Validator.
|
|
486
|
+
@example
|
|
487
|
+
// Assume em1 is a preexisting EntityManager.
|
|
488
|
+
const timeLimitType = em1.metadataStore.getAsEntityType("TimeLimit");
|
|
489
|
+
const maxTimeProperty = timeLimitType.getProperty("maxTime");
|
|
490
|
+
// Validates that the value of the maxTime property on TimeLimit is a duration.
|
|
491
|
+
maxTimeProperty.validators.push(Validator.duration());
|
|
492
|
+
@returns {Validator} A new Validator
|
|
493
|
+
*/
|
|
494
|
+
static duration = function () {
|
|
495
|
+
let valFn = function (v) {
|
|
496
|
+
if (v == null)
|
|
497
|
+
return true;
|
|
498
|
+
return core.isDuration(v);
|
|
499
|
+
};
|
|
500
|
+
return new Validator("duration", valFn);
|
|
501
|
+
};
|
|
502
|
+
/**
|
|
503
|
+
Returns a standard numeric data type Validator.
|
|
504
|
+
@example
|
|
505
|
+
// Assume em1 is a preexisting EntityManager.
|
|
506
|
+
const orderType = em1.metadataStore.getAsEntityType("Order");
|
|
507
|
+
const freightProperty = orderType.getProperty("freight");
|
|
508
|
+
// Validates that the value of the freight property on Order is a number.
|
|
509
|
+
freightProperty.validators.push(Validator.number());
|
|
510
|
+
@returns {Validator} A new Validator
|
|
511
|
+
*/
|
|
512
|
+
// TODO: may need to have seperate logic for single.
|
|
513
|
+
static number = function (context) {
|
|
514
|
+
let valFn = function (v, ctx) {
|
|
515
|
+
if (v == null)
|
|
516
|
+
return true;
|
|
517
|
+
if (typeof v === "string" && ctx && ctx.allowString) {
|
|
518
|
+
v = parseFloat(v);
|
|
519
|
+
}
|
|
520
|
+
return (typeof v === "number" && !isNaN(v));
|
|
521
|
+
};
|
|
522
|
+
return new Validator("number", valFn, context);
|
|
523
|
+
};
|
|
524
|
+
/** Another name for {@link Validator.number}, registered as `double` so that metadata naming it imports. The validator it returns is named `number`. */
|
|
525
|
+
static double = Validator.number;
|
|
526
|
+
/** Another name for {@link Validator.number}, registered as `single` so that metadata naming it imports. The validator it returns is named `number`. */
|
|
527
|
+
static single = Validator.number;
|
|
528
|
+
/**
|
|
529
|
+
Returns a standard large integer data type - 64 bit - Validator.
|
|
530
|
+
@example
|
|
531
|
+
// Assume em1 is a preexisting EntityManager.
|
|
532
|
+
const orderType = em1.metadataStore.getAsEntityType("Order");
|
|
533
|
+
const freightProperty = orderType.getProperty("freight");
|
|
534
|
+
// Validates that the value of the freight property on Order is within the range of a 64 bit integer.
|
|
535
|
+
freightProperty.validators.push(Validator.int64());
|
|
536
|
+
@returns {Validator} A new Validator
|
|
537
|
+
*/
|
|
538
|
+
static integer = function (context) {
|
|
539
|
+
let valFn = function (v, ctx) {
|
|
540
|
+
if (v == null)
|
|
541
|
+
return true;
|
|
542
|
+
if (typeof v === "string" && ctx && ctx.allowString) {
|
|
543
|
+
v = parseInt(v, 10);
|
|
544
|
+
}
|
|
545
|
+
return (typeof v === "number") && (!isNaN(v)) && Math.floor(v) === v;
|
|
546
|
+
};
|
|
547
|
+
return new Validator("integer", valFn, context);
|
|
548
|
+
};
|
|
549
|
+
/** Another name for {@link Validator.integer}, and the data-type validator for {@link DataType.Int64}: it checks that the value is a whole number, with no range check. The validator it returns is named `integer`. */
|
|
550
|
+
static int64 = Validator.integer;
|
|
551
|
+
/**
|
|
552
|
+
Returns a standard 32 bit integer data type Validator.
|
|
553
|
+
@example
|
|
554
|
+
// Assume em1 is a preexisting EntityManager.
|
|
555
|
+
const orderType = em1.metadataStore.getAsEntityType("Order");
|
|
556
|
+
const freightProperty = orderType.getProperty("freight");
|
|
557
|
+
freightProperty.validators.push(Validator.int32());
|
|
558
|
+
@returns {Validator} A new Validator
|
|
559
|
+
*/
|
|
560
|
+
static int32 = function (context) {
|
|
561
|
+
return intRangeValidatorCtor("int32", INT32_MIN, INT32_MAX, context)();
|
|
562
|
+
};
|
|
563
|
+
/**
|
|
564
|
+
Returns a standard 16 bit integer data type Validator.
|
|
565
|
+
@example
|
|
566
|
+
// Assume em1 is a preexisting EntityManager.
|
|
567
|
+
const orderType = em1.metadataStore.getAsEntityType("Order");
|
|
568
|
+
const freightProperty = orderType.getProperty("freight");
|
|
569
|
+
// Validates that the value of the freight property on Order is within the range of a 16 bit integer.
|
|
570
|
+
freightProperty.validators.push(Validator.int16());
|
|
571
|
+
@returns {Validator} A new Validator
|
|
572
|
+
*/
|
|
573
|
+
static int16 = function (context) {
|
|
574
|
+
return intRangeValidatorCtor("int16", INT16_MIN, INT16_MAX, context)();
|
|
575
|
+
};
|
|
576
|
+
/**
|
|
577
|
+
Returns a standard byte data type Validator. (This is a integer between 0 and 255 inclusive for js purposes).
|
|
578
|
+
@example
|
|
579
|
+
// Assume em1 is a preexisting EntityManager.
|
|
580
|
+
const orderType = em1.metadataStore.getAsEntityType("Order");
|
|
581
|
+
const freightProperty = orderType.getProperty("freight");
|
|
582
|
+
// Validates that the value of the freight property on Order is a byte: an integer from 0 to 255.
|
|
583
|
+
// Probably not a very good validation to place on the freight property.
|
|
584
|
+
freightProperty.validators.push(Validator.byte());
|
|
585
|
+
@returns {Validator} A new Validator
|
|
586
|
+
*/
|
|
587
|
+
static byte = function (context) {
|
|
588
|
+
return intRangeValidatorCtor("byte", BYTE_MIN, BYTE_MAX, context)();
|
|
589
|
+
};
|
|
590
|
+
/**
|
|
591
|
+
Returns a standard boolean data type Validator.
|
|
592
|
+
@example
|
|
593
|
+
// Assume em1 is a preexisting EntityManager.
|
|
594
|
+
const productType = em1.metadataStore.getAsEntityType("Product");
|
|
595
|
+
const discontinuedProperty = productType.getProperty("isDiscontinued");
|
|
596
|
+
// Validates that the value of the isDiscontinued property on Product is a boolean
|
|
597
|
+
discontinuedProperty.validators.push(Validator.bool());
|
|
598
|
+
@returns {Validator} A new Validator
|
|
599
|
+
*/
|
|
600
|
+
static bool = function () {
|
|
601
|
+
let valFn = function (v) {
|
|
602
|
+
if (v == null)
|
|
603
|
+
return true;
|
|
604
|
+
return (v === true) || (v === false);
|
|
605
|
+
};
|
|
606
|
+
return new Validator("bool", valFn);
|
|
607
|
+
};
|
|
608
|
+
/** Returns a Validator named `none` that accepts every value. It is the data-type validator for {@link DataType.Binary} and {@link DataType.Undefined}. */
|
|
609
|
+
static none = function () {
|
|
610
|
+
let valFn = function (v) {
|
|
611
|
+
return true;
|
|
612
|
+
};
|
|
613
|
+
return new Validator("none", valFn);
|
|
614
|
+
};
|
|
615
|
+
/**
|
|
616
|
+
Returns a standard date data type Validator.
|
|
617
|
+
@example
|
|
618
|
+
// Assume em1 is a preexisting EntityManager.
|
|
619
|
+
const orderType = em1.metadataStore.getAsEntityType("Order");
|
|
620
|
+
const orderDateProperty = orderType.getProperty("orderDate");
|
|
621
|
+
// Validates that the value of the orderDate property on Order is a date
|
|
622
|
+
orderDateProperty.validators.push(Validator.date());
|
|
623
|
+
@returns {Validator} A new Validator
|
|
624
|
+
*/
|
|
625
|
+
static date = function () {
|
|
626
|
+
let valFn = function (v) {
|
|
627
|
+
if (v == null)
|
|
628
|
+
return true;
|
|
629
|
+
if (typeof v === "string") {
|
|
630
|
+
try {
|
|
631
|
+
return !isNaN(Date.parse(v));
|
|
632
|
+
// old code
|
|
633
|
+
// return __isDate(new Date(v));
|
|
634
|
+
}
|
|
635
|
+
catch (e) {
|
|
636
|
+
return false;
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
else {
|
|
640
|
+
return core.isDate(v);
|
|
641
|
+
}
|
|
642
|
+
};
|
|
643
|
+
return new Validator("date", valFn);
|
|
644
|
+
};
|
|
645
|
+
/**
|
|
646
|
+
Returns a credit card number validator
|
|
647
|
+
Performs a luhn algorithm checksum test for plausability
|
|
648
|
+
catches simple mistakes; only service knows for sure
|
|
649
|
+
@example
|
|
650
|
+
// Assume em is a preexisting EntityManager.
|
|
651
|
+
const personType = em.metadataStore.getAsEntityType("Person");
|
|
652
|
+
const creditCardProperty = personType.getProperty("creditCard");
|
|
653
|
+
// Validates that the value of the Person.creditCard property is credit card.
|
|
654
|
+
creditCardProperty.validators.push(Validator.creditCard());
|
|
655
|
+
@param [context] {Object} optional parameters to pass through to validation constructor
|
|
656
|
+
@returns {Validator} A new Validator
|
|
657
|
+
*/
|
|
658
|
+
static creditCard = function (context) {
|
|
659
|
+
function valFn(v) {
|
|
660
|
+
if (v == null || v === '')
|
|
661
|
+
return true;
|
|
662
|
+
if (typeof (v) !== 'string')
|
|
663
|
+
return false;
|
|
664
|
+
v = v.replace(/(\-|\s)/g, ""); // remove dashes and spaces
|
|
665
|
+
if (!v || /\D/.test(v))
|
|
666
|
+
return false; // all digits, not empty
|
|
667
|
+
return luhn(v);
|
|
668
|
+
}
|
|
669
|
+
return new Validator('creditCard', valFn, context);
|
|
670
|
+
};
|
|
671
|
+
/**
|
|
672
|
+
Returns a regular expression validator; the expression must be specified
|
|
673
|
+
@example
|
|
674
|
+
// Add validator to a property. Assume em is a preexisting EntityManager.
|
|
675
|
+
const customerType = em.metadataStore.getAsEntityType("Customer");
|
|
676
|
+
const regionProperty = customerType.getProperty("region");
|
|
677
|
+
// Validates that the value of Customer.region is 2 char uppercase alpha.
|
|
678
|
+
regionProperty.validators.push(Validator.regularExpression({ expression: '^[A-Z]{2}$' }));
|
|
679
|
+
@param context - An object with `expression` (string) - String form of the regular expression to apply.
|
|
680
|
+
@returns {Validator} A new Validator
|
|
681
|
+
*/
|
|
682
|
+
static regularExpression = function (context) {
|
|
683
|
+
function valFn(v, ctx) {
|
|
684
|
+
// do not invalidate if empty; use a separate required test
|
|
685
|
+
if (v == null || v === '')
|
|
686
|
+
return true;
|
|
687
|
+
if (typeof (v) !== 'string')
|
|
688
|
+
return false;
|
|
689
|
+
try {
|
|
690
|
+
let re = new RegExp(ctx.expression);
|
|
691
|
+
return re.test(v);
|
|
692
|
+
}
|
|
693
|
+
catch (e) {
|
|
694
|
+
throw new Error('Missing or invalid expression parameter to regExp validator');
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
return new Validator('regularExpression', valFn, context);
|
|
698
|
+
};
|
|
699
|
+
/**
|
|
700
|
+
Returns the email address validator
|
|
701
|
+
@example
|
|
702
|
+
// Assume em is a preexisting EntityManager.
|
|
703
|
+
const userType = em.metadataStore.getAsEntityType("User");
|
|
704
|
+
const emailProperty = userType.getProperty("email");
|
|
705
|
+
// Validates that the value of the User.email property is an email address.
|
|
706
|
+
emailProperty.validators.push(Validator.emailAddress());
|
|
707
|
+
@param [context] {Object} optional parameters to pass through to validation constructor
|
|
708
|
+
@returns {Validator} A new Validator
|
|
709
|
+
*/
|
|
710
|
+
static emailAddress = function (context) {
|
|
711
|
+
// See https://github.com/srkirkland/DataAnnotationsExtensions/blob/master/DataAnnotationsExtensions/EmailAttribute.cs
|
|
712
|
+
let reEmailAddress = /^((([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;
|
|
713
|
+
return makeRegExpValidator('emailAddress', reEmailAddress, null, context);
|
|
714
|
+
};
|
|
715
|
+
/**
|
|
716
|
+
Returns the phone validator
|
|
717
|
+
Provides basic assertions on the format and will help to eliminate most nonsense input
|
|
718
|
+
Matches:
|
|
719
|
+
International dialing prefix: one of nothing, `+`, `0` or `0000` (with or without a trailing break character, if not '+': [-/. ])
|
|
720
|
+
```ts
|
|
721
|
+
((\+)|(0(\d+)?[-/.\s]))
|
|
722
|
+
```
|
|
723
|
+
Country code: nothing, or `1` to `999` (with or without a trailing break character: [-/. ])
|
|
724
|
+
```ts
|
|
725
|
+
[1-9]\d{,2}[-/.\s]?
|
|
726
|
+
```
|
|
727
|
+
Area code: `(0)` to `(000000)`, or `0` to `000000` (with or without a trailing break character: [-/. ])
|
|
728
|
+
```ts
|
|
729
|
+
((\(\d{1,6}\)|\d{1,6})[-/.\s]?)?
|
|
730
|
+
```
|
|
731
|
+
Local: one or more digits (with or without a trailing break character: [-/. ])
|
|
732
|
+
```ts
|
|
733
|
+
(\d+[-/.\s]?)+\d+
|
|
734
|
+
```
|
|
735
|
+
@example
|
|
736
|
+
// Assume em is a preexisting EntityManager.
|
|
737
|
+
const customerType = em.metadataStore.getAsEntityType("Customer");
|
|
738
|
+
const phoneProperty = customerType.getProperty("phone");
|
|
739
|
+
// Validates that the value of the Customer.phone property is phone.
|
|
740
|
+
phoneProperty.validators.push(Validator.phone());
|
|
741
|
+
@param [context] {Object} optional parameters to pass through to validation constructor
|
|
742
|
+
@returns {Validator} A new Validator
|
|
743
|
+
*/
|
|
744
|
+
static phone = function (context) {
|
|
745
|
+
// See https://github.com/srkirkland/DataAnnotationsExtensions/blob/master/DataAnnotationsExtensions/Expressions.cs
|
|
746
|
+
let rePhone = /^((\+|(0(\d+)?[-/.\s]?))[1-9]\d{0,2}[-/.\s]?)?((\(\d{1,6}\)|\d{1,6})[-/.\s]?)?(\d+[-/.\s]?)+\d+$/;
|
|
747
|
+
return makeRegExpValidator('phone', rePhone, null, context);
|
|
748
|
+
};
|
|
749
|
+
/**
|
|
750
|
+
Returns the URL (protocol required) validator
|
|
751
|
+
@example
|
|
752
|
+
// Assume em is a preexisting EntityManager.
|
|
753
|
+
const supplierType = em.metadataStore.getAsEntityType("Supplier");
|
|
754
|
+
const homePageProperty = supplierType.getProperty("homePage");
|
|
755
|
+
// Validates that the value of the Supplier.homePage property is a URL.
|
|
756
|
+
homePageProperty.validators.push(Validator.url());
|
|
757
|
+
@param [context] {Object} optional parameters to pass through to validation constructor
|
|
758
|
+
@returns {Validator} A new Validator
|
|
759
|
+
*/
|
|
760
|
+
static url = function (context) {
|
|
761
|
+
//See https://github.com/srkirkland/DataAnnotationsExtensions/blob/master/DataAnnotationsExtensions/UrlAttribute.cs
|
|
762
|
+
let reUrlProtocolRequired = /^(https?|ftp):\/\/(((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-fA-F]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|([a-zA-Z][\-a-zA-Z0-9]*)|((([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-fA-F]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-fA-F]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-fA-F]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-fA-F]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/;
|
|
763
|
+
return makeRegExpValidator('url', reUrlProtocolRequired, null, context);
|
|
764
|
+
};
|
|
765
|
+
/**
|
|
766
|
+
Creates a regular expression validator with a fixed expression.
|
|
767
|
+
Many of the stock validators are built with this factory method.
|
|
768
|
+
Their expressions are often derived from
|
|
769
|
+
https://github.com/srkirkland/DataAnnotationsExtensions/blob/master/DataAnnotationsExtensions
|
|
770
|
+
You can try many of them at http://dataannotationsextensions.org/
|
|
771
|
+
@example
|
|
772
|
+
// Make a zipcode validator
|
|
773
|
+
const zipValidator = Validator.makeRegExpValidator(
|
|
774
|
+
"zipVal",
|
|
775
|
+
/^\d{5}([\-]\d{4})?$/,
|
|
776
|
+
"The %displayName% '%value%' is not a valid U.S. zipcode");
|
|
777
|
+
// Register it.
|
|
778
|
+
Validator.register(zipValidator);
|
|
779
|
+
// Add it to a data property. Assume em is a preexisting EntityManager.
|
|
780
|
+
const custType = em.metadataStore.getAsEntityType("Customer");
|
|
781
|
+
const zipProperty = custType.getProperty("postalCode");
|
|
782
|
+
zipProperty.validators.push(zipValidator);
|
|
783
|
+
@param validatorName {String} name of this validator
|
|
784
|
+
@param expression {String | RegExp} regular expression to apply
|
|
785
|
+
@param [defaultMessage] {String} default message for failed validations
|
|
786
|
+
@param [context] {Object} optional parameters to pass through to validation constructor
|
|
787
|
+
@returns {Validator} A new Validator
|
|
788
|
+
*/
|
|
789
|
+
static makeRegExpValidator = makeRegExpValidator;
|
|
790
|
+
}
|
|
791
|
+
Validator.prototype._$typeName = "Validator";
|
|
792
|
+
// register all validators
|
|
793
|
+
core.objectForEach(Validator, function (key, value) {
|
|
794
|
+
if (typeof (value) !== "function") {
|
|
795
|
+
return;
|
|
796
|
+
}
|
|
797
|
+
if (key === "fromJSON" || key === "register" ||
|
|
798
|
+
key === "registerFactory" || key === "makeRegExpValidator") {
|
|
799
|
+
return;
|
|
800
|
+
}
|
|
801
|
+
config.registerFunction(value, "Validator." + key);
|
|
802
|
+
});
|
|
803
|
+
function formatTemplate(template, vars, ownPropertiesOnly = false) {
|
|
804
|
+
if (!vars)
|
|
805
|
+
return template;
|
|
806
|
+
return template.replace(/%([^%]+)%/g, function (_, key) {
|
|
807
|
+
let valOrFn;
|
|
808
|
+
if (ownPropertiesOnly) {
|
|
809
|
+
valOrFn = vars.hasOwnProperty(key) ? vars[key] : '';
|
|
810
|
+
}
|
|
811
|
+
else {
|
|
812
|
+
valOrFn = vars[key];
|
|
813
|
+
}
|
|
814
|
+
if (valOrFn != null) {
|
|
815
|
+
if (core.isFunction(valOrFn)) {
|
|
816
|
+
return valOrFn(vars);
|
|
817
|
+
}
|
|
818
|
+
else {
|
|
819
|
+
return valOrFn;
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
else {
|
|
823
|
+
return "";
|
|
824
|
+
}
|
|
825
|
+
});
|
|
826
|
+
}
|
|
827
|
+
function intRangeValidatorCtor(validatorName, minValue, maxValue, context) {
|
|
828
|
+
context = context || {};
|
|
829
|
+
if (minValue !== undefined) {
|
|
830
|
+
context.min = minValue;
|
|
831
|
+
}
|
|
832
|
+
if (maxValue !== undefined) {
|
|
833
|
+
context.max = maxValue;
|
|
834
|
+
}
|
|
835
|
+
let templateExists = context.messageTemplate || Validator.messageTemplates[validatorName];
|
|
836
|
+
if (!templateExists) {
|
|
837
|
+
Validator.messageTemplates[validatorName] = core.formatString("'%displayName%' must be an integer between the values of %1 and %2", minValue, maxValue);
|
|
838
|
+
}
|
|
839
|
+
return function () {
|
|
840
|
+
let valFn = function (v, ctx) {
|
|
841
|
+
if (v == null)
|
|
842
|
+
return true;
|
|
843
|
+
if (typeof v === "string" && ctx && ctx.allowString) {
|
|
844
|
+
v = parseInt(v, 0);
|
|
845
|
+
}
|
|
846
|
+
if ((typeof v === "number") && (!isNaN(v)) && Math.floor(v) === v) {
|
|
847
|
+
if (minValue != null && v < minValue) {
|
|
848
|
+
return false;
|
|
849
|
+
}
|
|
850
|
+
if (maxValue != null && v > maxValue) {
|
|
851
|
+
return false;
|
|
852
|
+
}
|
|
853
|
+
return true;
|
|
854
|
+
}
|
|
855
|
+
else {
|
|
856
|
+
return false;
|
|
857
|
+
}
|
|
858
|
+
};
|
|
859
|
+
return new Validator(validatorName, valFn, context);
|
|
860
|
+
};
|
|
861
|
+
}
|
|
862
|
+
export function makeRegExpValidator(validatorName, expression, defaultMessage, context) {
|
|
863
|
+
if (defaultMessage) {
|
|
864
|
+
Validator.messageTemplates[validatorName] = defaultMessage;
|
|
865
|
+
}
|
|
866
|
+
let re = (typeof (expression) === 'string') ? new RegExp(expression) : expression;
|
|
867
|
+
let valFn = function (v) {
|
|
868
|
+
// do not invalidate if empty; use a separate required test
|
|
869
|
+
if (v == null || v === '')
|
|
870
|
+
return true;
|
|
871
|
+
if (typeof (v) !== 'string')
|
|
872
|
+
return false;
|
|
873
|
+
return re.test(v);
|
|
874
|
+
};
|
|
875
|
+
return new Validator(validatorName, valFn, context);
|
|
876
|
+
}
|
|
877
|
+
// http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#JavaScript
|
|
878
|
+
// function luhn(a: string, b: number, c: number, d: number, e: number) {
|
|
879
|
+
// for (d = +a[b = a.length - 1], e = 0; b--; ) {
|
|
880
|
+
// c = +a[b], d += ++e % 2 ? 2 * c % 10 + (c > 4) : c;
|
|
881
|
+
// }
|
|
882
|
+
// return !(d % 10);
|
|
883
|
+
// };
|
|
884
|
+
let luhn = (function () {
|
|
885
|
+
let luhnArr = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9];
|
|
886
|
+
return function (str) {
|
|
887
|
+
let counter = 0;
|
|
888
|
+
let incNum;
|
|
889
|
+
let odd = false;
|
|
890
|
+
let temp = String(str).replace(/[^\d]/g, "");
|
|
891
|
+
if (temp.length === 0)
|
|
892
|
+
return false;
|
|
893
|
+
for (let i = temp.length - 1; i >= 0; --i) {
|
|
894
|
+
incNum = parseInt(temp.charAt(i), 10);
|
|
895
|
+
counter += (odd = !odd) ? incNum : luhnArr[incNum];
|
|
896
|
+
}
|
|
897
|
+
return (counter % 10 === 0);
|
|
898
|
+
};
|
|
899
|
+
})();
|
|
900
|
+
/**
|
|
901
|
+
Describes one failed validation: which validator failed, on which property, and the message to
|
|
902
|
+
show. An entity's current errors are in {@link EntityAspect.getValidationErrors}. The errors a
|
|
903
|
+
server reports for a failed save are added there too, with {@link ValidationError.isServerError} set.
|
|
904
|
+
*/
|
|
905
|
+
export class ValidationError {
|
|
906
|
+
/** The {@link Validator} that produced this error. `undefined` for an error from the server or one created without a validator. __Read Only__ */
|
|
907
|
+
validator;
|
|
908
|
+
/** The key that identifies this error among an entity's validation errors: the validator's name (or the error name), then `:` and the property name if there is one. Adding an error with the same key replaces the old one. __Read Only__ */
|
|
909
|
+
key;
|
|
910
|
+
/** The context the error was created with - for a validator, its context when it ran, which for a property error includes `entity`, `property`, `propertyName` and `value`. __Read Only__ */
|
|
911
|
+
context;
|
|
912
|
+
/** The error message. __Read Only__ */
|
|
913
|
+
errorMessage;
|
|
914
|
+
/** The {@link DataProperty} or {@link NavigationProperty} this error is about, or `undefined` for an entity-level error. __Read Only__ */
|
|
915
|
+
property; // IProperty
|
|
916
|
+
/** The name of the property this error is about - a property path, such as `address.city`, for a property of a complex object - or `undefined` for an entity-level error. __Read Only__ */
|
|
917
|
+
propertyName;
|
|
918
|
+
/** Whether this error came from the server in a failed save. Server errors do not block a save, and are cleared when the property is changed or the entity is saved again. __Read Only__ */
|
|
919
|
+
isServerError;
|
|
920
|
+
/**
|
|
921
|
+
Creates a validation error. Applications usually add one with
|
|
922
|
+
{@link EntityAspect.addValidationError} after creating it here.
|
|
923
|
+
@param validator - The Validator that found the error, or `null` for an error found some other way.
|
|
924
|
+
@param context - The context to record with the error: for a property, its `entity`, `property`,
|
|
925
|
+
`propertyName` and `value`.
|
|
926
|
+
@param errorMessage - The message to show.
|
|
927
|
+
@param key - Identifies the error among the entity's errors. If not given, it is built from the
|
|
928
|
+
validator's name - or, without a validator, the error message - and the property name; see
|
|
929
|
+
{@link ValidationError.getKey}.
|
|
930
|
+
*/
|
|
931
|
+
constructor(validator, context, errorMessage, key) {
|
|
932
|
+
// Error is with isInstanceOf(Validator)
|
|
933
|
+
assertParam(validator, "validator").isOptional().isInstanceOf(Validator).check();
|
|
934
|
+
assertParam(errorMessage, "errorMessage").isNonEmptyString().check();
|
|
935
|
+
assertParam(key, "key").isOptional().isNonEmptyString().check();
|
|
936
|
+
this.validator = validator || undefined;
|
|
937
|
+
context = context || {};
|
|
938
|
+
this.context = context;
|
|
939
|
+
this.errorMessage = errorMessage;
|
|
940
|
+
this.property = context.property;
|
|
941
|
+
this.propertyName = context.propertyName || (context.property && context.property.name);
|
|
942
|
+
if (key) {
|
|
943
|
+
this.key = key;
|
|
944
|
+
}
|
|
945
|
+
else {
|
|
946
|
+
this.key = ValidationError.getKey(validator || errorMessage, this.propertyName);
|
|
947
|
+
}
|
|
948
|
+
this.isServerError = false;
|
|
949
|
+
}
|
|
950
|
+
/**
|
|
951
|
+
Composes a ValidationError 'key' given a validator or an errorName and an optional propertyName
|
|
952
|
+
@param validatorOrErrorName - A Validator, or an "error name" if no validator is available.
|
|
953
|
+
@param [propertyName] A property name
|
|
954
|
+
@returns {String} A ValidationError 'key'
|
|
955
|
+
*/
|
|
956
|
+
static getKey(validatorOrErrorName, propertyName) {
|
|
957
|
+
let name = (typeof validatorOrErrorName === 'string') ? validatorOrErrorName : validatorOrErrorName.name;
|
|
958
|
+
return name + (propertyName ? ":" + propertyName : "");
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
//# sourceMappingURL=validate.js.map
|