comprodls-sdk 2.107.0 → 2.109.0-thor.1

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.
@@ -289,6 +289,7 @@ exports.AUTH_API_URLS = {
289
289
  validateSpaceCode: '/accounts/{accountid}/space-code/validate',
290
290
  validateClassCode: '/accounts/{accountid}/class-code/validate',
291
291
  joinInstituteSpace: '/accounts/{accountid}/join-institute-space',
292
+ provisionStudentInInstitutionalSpace: '/accounts/{accountid}/student/join-institute-space',
292
293
  provisionSpacesToStudent: '/accounts/{accountId}/student/provision-spaces',
293
294
  provisionSpacesToTeacher: '/accounts/{accountId}/teacher/provision-spaces',
294
295
  shadowProvision: '/org/{orgId}/shadow-provision',
@@ -371,6 +372,7 @@ exports.AUTHEXTN_API_URLS = {
371
372
 
372
373
  //Space related API
373
374
  entitleBulkUsersToProducts: '/accounts/{accountid}/entitle-users/bulk',
375
+ deleteUserAccount : '/accounts/{accountid}/ext-users/{ext_user_id}',
374
376
 
375
377
  // Assigned Path APIs
376
378
  userAssignedPaths: '/org/{orgid}/classes/{classid}/assigned-paths/{assignedpathid}/enroll-user/multi',
@@ -731,7 +733,9 @@ function setupAPIToken(request, token) {
731
733
  var ERROR_TYPES = {
732
734
  API_ERROR: 'API_ERROR',
733
735
  SDK_ERROR: 'SDK_ERROR',
734
- CHANNEL_SUBSCRIPTION: 'CHANNEL_SUBSCRIPTION'
736
+ CHANNEL_SUBSCRIPTION: 'CHANNEL_SUBSCRIPTION',
737
+ UNEXPECTED_ERROR: 'UNEXPECTED_ERROR',
738
+ POLLING_INITIATION: 'POLLING_INITIATION'
735
739
  };
736
740
 
737
741
  var ERROR_CATEGORY = {
@@ -1006,13 +1010,129 @@ module.exports = {
1006
1010
  * comproDLS SDK Validator Helper Module
1007
1011
  * This module contains validation helper functions for comproDLS SDK
1008
1012
  ************************************************************/
1009
- var validator = require('validate.js');
1013
+
1010
1014
  var errors = require('./errors');
1011
1015
  var DLSError = errors.DLSError;
1012
1016
 
1013
- exports.validate = validate;
1014
- exports.isAuthenticated = validateIsAuthenticated;
1015
- exports.isAuthenticatedV2 = validateIsAuthenticatedV2;
1017
+ /*********************************
1018
+ * Core validator utilities
1019
+ * Each validator follows the signature:
1020
+ * fn(field, value, options) → DLSError | undefined
1021
+ *
1022
+ * - field : the constraint key name e.g. 'organization', 'token', 'token.access_token'
1023
+ * - value : the value from the options object for that field
1024
+ * - options : the rule config, can be `true` or `{ message: '...' }`
1025
+ * For `contains`, options is a string or array of required keys.
1026
+ *
1027
+ * Returning a DLSError which stops validation immediately.
1028
+ * Returning undefined means the check passed.
1029
+ **********************************/
1030
+ var validators = {
1031
+ /**
1032
+ * Fails if value is null, undefined, or blank/whitespace-only string or empty object.
1033
+ */
1034
+ presence: function(field, value, options) {
1035
+ if (value === undefined || value === null || value === '' ||
1036
+ (typeof value == 'string' && value.trim() === '') ||
1037
+ (typeof value == 'object' && Object.keys(value).length === 0)
1038
+ ) {
1039
+ return createError(options.message || field + ' can\'t be blank');
1040
+ }
1041
+ },
1042
+
1043
+ /**
1044
+ * Fails if value is not a string.
1045
+ */
1046
+ isString: function(field, value, options) {
1047
+ if (typeof value !== 'string') {
1048
+ return createError(options.message || field + ' is not a valid string');
1049
+ }
1050
+ },
1051
+
1052
+ /**
1053
+ * Fails if value is not an object.
1054
+ */
1055
+ isObject: function(field, value, options) {
1056
+ if (typeof value !== 'object' || Array.isArray(value)) {
1057
+ return createError(options.message || field + ' is not a valid object');
1058
+ }
1059
+ },
1060
+
1061
+ /**
1062
+ * Fails if the object does not have the required key(s).
1063
+ */
1064
+ contains: function(field, value, options) {
1065
+ var keys = Array.isArray(options) ? options : typeof options === 'string' ? [options] : [];
1066
+
1067
+ for (var i = 0; i < keys.length; i++) {
1068
+ var requiredKey = keys[i];
1069
+
1070
+ if (!value.hasOwnProperty(requiredKey)) {
1071
+ return createError(options.message || field + ' does not contain ' + requiredKey);
1072
+ }
1073
+ }
1074
+ }
1075
+ };
1076
+
1077
+ /*********************************
1078
+ * Core validate function
1079
+ *
1080
+ * Iterates over each field in constraints, resolves its value from options,
1081
+ * then runs each rule's validator function in order.
1082
+ * Returns the first error encountered or undefined if all pass.
1083
+ *
1084
+ * @param {Object} options - The input object to validate
1085
+ * @param {Object} constraints - Map of field names to their rule constraints
1086
+ * @returns {DLSError | undefined}
1087
+ **********************************/
1088
+ function validate(options, constraints) {
1089
+ for (var field in constraints) {
1090
+ var fieldConstraintsObj = constraints[field];
1091
+ var value = getValue(options, field);
1092
+
1093
+ for (var ruleName in fieldConstraintsObj) {
1094
+ var ruleOptions = fieldConstraintsObj[ruleName];
1095
+ var validatorFn = validators[ruleName];
1096
+
1097
+ if (!validatorFn) { continue; }
1098
+
1099
+ // Pass field name, field value, and field's rule constraint value to the validator function
1100
+ var error = validatorFn(field, value, ruleOptions);
1101
+ if (error) { return error; }
1102
+ }
1103
+ }
1104
+
1105
+ return undefined;
1106
+ }
1107
+
1108
+ /*********************************
1109
+ * Private helpers
1110
+ **********************************/
1111
+ function getValue(obj, path) {
1112
+ var keys = path.split('.');
1113
+ var result = obj;
1114
+
1115
+ for (var i = 0; i < keys.length; i++) {
1116
+ if (result === undefined || result === null) { return undefined; }
1117
+ result = result[keys[i]];
1118
+ }
1119
+
1120
+ return result;
1121
+ }
1122
+
1123
+ function createError(message) {
1124
+ var msg = message || 'Validation error';
1125
+ msg = msg.charAt(0).toUpperCase() + msg.slice(1);
1126
+
1127
+ return new DLSError(errors.ERROR_TYPES.SDK_ERROR, {
1128
+ message: msg,
1129
+ description: msg
1130
+ });
1131
+ }
1132
+
1133
+ /*********************************
1134
+ * Exported auth validators
1135
+ **********************************/
1016
1136
 
1017
1137
  /**
1018
1138
  * This function validates if the SDK instance is authenticated.
@@ -1029,22 +1149,10 @@ function validateIsAuthenticatedV2(orgId, token) {
1029
1149
  return new DLSError(errors.ERROR_TYPES.SDK_ERROR, errObj);
1030
1150
  };
1031
1151
 
1032
- function validate(options, constraints) {
1033
- var err = {};
1034
- var validation_errors = validator(options, constraints);
1035
- if (validation_errors) {
1036
- for (var validation_error in validation_errors) {
1037
- err.message = err.description = validation_errors[validation_error][0];
1038
- err = new DLSError(errors.ERROR_TYPES.SDK_ERROR, err);
1039
- return err;
1040
- }
1041
- } else {
1042
- return undefined;
1043
- }
1044
- };
1045
-
1046
1152
  /**
1047
- * This function is deprecated. Please use validateIsAuthenticatedV2 instead.
1153
+ * Validates if SDK instance is authenticated by checking presence of orgId and token.
1154
+ * @param {String} orgId - Organization ID
1155
+ * @param {Object} token - Token object { access_token: 'string' }
1048
1156
  */
1049
1157
  function validateIsAuthenticated(orgId, token) {
1050
1158
  var validate_options = {
@@ -1052,52 +1160,26 @@ function validateIsAuthenticated(orgId, token) {
1052
1160
  'token': token
1053
1161
  };
1054
1162
 
1163
+ var errMsg = 'SDK Instance does not have valid orgid or token. ' +
1164
+ 'Please authenticate using authWithCredentials or authWithToken method.';
1165
+
1055
1166
  var validate_constraints = {
1056
1167
  'organization': {
1057
- 'presence': {
1058
- 'message' : '^SDK Instance does not have valid orgid or token. Please authenticate using authWithCredentials or authWithToken method.'
1059
- }
1168
+ 'presence': { 'message': errMsg }
1060
1169
  },
1061
1170
  'token': {
1062
- 'presence': {
1063
- 'message' : '^SDK Instance does not have valid orgid or token. Please authenticate using authWithCredentials or authWithToken method.'
1064
- }
1171
+ 'presence': { 'message': errMsg }
1065
1172
  }
1066
1173
  };
1067
1174
 
1068
1175
  return validate(validate_options, validate_constraints);
1069
1176
  };
1070
1177
 
1071
- /*********************************
1072
- * Private Function definitions
1073
- **********************************/
1074
- validator.validators.isString = function(value, options) {
1075
- if (!validator.isString(value)) {
1076
- return options.message || 'is not a valid string';
1077
- }
1078
- };
1079
-
1080
- validator.validators.isObject = function(value, options) {
1081
- if (!validator.isObject(value)) {
1082
- return options.message || 'is not a valid object';
1083
- }
1084
- };
1085
-
1086
- validator.validators.contains = function(value, options) {
1087
- if (validator.isArray(options)) {
1088
- for (var key in options) {
1089
- if (!value || !value.hasOwnProperty(options[key])) {
1090
- return options.message || 'does not contain ' + options[key];
1091
- }
1092
- }
1093
- } else if (validator.isString(options)) {
1094
- if (!value || !value.hasOwnProperty(options)) {
1095
- return options.message || 'does not contain ' + options;
1096
- }
1097
- }
1098
- };
1178
+ exports.validate = validate;
1179
+ exports.isAuthenticated = validateIsAuthenticated;
1180
+ exports.isAuthenticatedV2 = validateIsAuthenticatedV2;
1099
1181
 
1100
- },{"./errors":6,"validate.js":44}],9:[function(require,module,exports){
1182
+ },{"./errors":6}],9:[function(require,module,exports){
1101
1183
  /*************************************************************************
1102
1184
  *
1103
1185
  * COMPRO CONFIDENTIAL
@@ -11300,39 +11382,45 @@ function changeSpaceCode(options) {
11300
11382
  */
11301
11383
  function joinInstituteSpace(options) {
11302
11384
  var self = this;
11303
- // Initializing promise
11304
- var dfd = q.defer();
11305
11385
 
11306
- if(options && options.ext_user_id &&
11307
- options.ext_role && options.space_code)
11308
- {
11309
- // Passed all validations, Contruct API url
11310
- var url = self.config.DEFAULT_HOSTS.AUTH +
11311
- self.config.AUTH_API_URLS.joinInstituteSpace;
11312
- url = helpers.api.constructAPIUrl(url, { accountid : self.accountId });
11313
-
11314
- // Setup request with URL and Params
11315
- var requestAPI = request.post(url)
11316
- .set('Content-Type', 'application/json')
11317
- .set('Accept', 'application/json')
11318
- .send(options);
11319
- if(self.traceid) { requestAPI.set('X-Amzn-Trace-Id', self.traceid); }
11386
+ return new Promise(function(resolve, reject) {
11387
+ if (options && options.ext_user_id && options.ext_role) {
11388
+ // Passed all validations, Contruct API url
11320
11389
 
11321
- requestAPI.end(function(error, response) {
11322
- if(error) {
11323
- err = new DLSError(helpers.errors.ERROR_TYPES.API_ERROR, error);
11324
- dfd.reject(err);
11390
+ var url;
11391
+ if (options.ext_role === 'student') {
11392
+ url = self.config.DEFAULT_HOSTS.AUTH +
11393
+ self.config.AUTH_API_URLS.provisionStudentInInstitutionalSpace;
11325
11394
  }
11326
- else { dfd.resolve(response.body); }
11327
- });
11328
- } else {
11329
- var err = {};
11330
- err.message = err.description = 'ext_user_id or ext_role or space_code not found in request options.';
11331
- err = new DLSError(helpers.errors.ERROR_TYPES.SDK_ERROR, err);
11332
- dfd.reject(err);
11333
- }
11395
+ else {
11396
+ url = self.config.DEFAULT_HOSTS.AUTH + self.config.AUTH_API_URLS.joinInstituteSpace;
11397
+ }
11398
+ url = helpers.api.constructAPIUrl(url, { accountid : self.accountId });
11334
11399
 
11335
- return dfd.promise;
11400
+ // Setup request with URL and Params
11401
+ var requestAPI = request.post(url)
11402
+ .set('Content-Type', 'application/json')
11403
+ .set('Accept', 'application/json');
11404
+ if(self.traceid) { requestAPI.set('X-Amzn-Trace-Id', self.traceid); }
11405
+
11406
+ requestAPI
11407
+ .send(options)
11408
+ .agent(keepaliveAgent)
11409
+ .end(function(error, response) {
11410
+ if (error) {
11411
+ var err = new DLSError(helpers.errors.ERROR_TYPES.API_ERROR, error);
11412
+ reject(err);
11413
+ }
11414
+ else { resolve(response.body); }
11415
+ });
11416
+ } else {
11417
+ var err = {};
11418
+ err.message = err.description = 'ext_user_id or ext_role not found' +
11419
+ ' in request options.';
11420
+ err = new DLSError(helpers.errors.ERROR_TYPES.SDK_ERROR, err);
11421
+ reject(err);
11422
+ }
11423
+ });
11336
11424
  }
11337
11425
 
11338
11426
  /**
@@ -11872,6 +11960,7 @@ function updateUserInformation(options) {
11872
11960
  };
11873
11961
  if(options.ref_id) { bodyParams.ref_id = options.ref_id; }
11874
11962
  if(options.ext_email) { bodyParams.ext_email = options.ext_email; }
11963
+ if(options.ext_username) { bodyParams.ext_username = options.ext_username; }
11875
11964
  if(options.ext_first_name) { bodyParams.ext_first_name = options.ext_first_name; }
11876
11965
  if(options.ext_last_name) { bodyParams.ext_last_name = options.ext_last_name; }
11877
11966
  if(options.address) { bodyParams.address = options.address; }
@@ -12066,7 +12155,8 @@ function spacesextn(accountId) {
12066
12155
  this.accountId = accountId;
12067
12156
  return {
12068
12157
  entitleBulkUsersToProducts: entitleBulkUsersToProducts.bind(this),
12069
- setupUser: setupUser.bind(this)
12158
+ setupUser: setupUser.bind(this),
12159
+ deleteUserAccount : deleteUserAccount.bind(this)
12070
12160
  };
12071
12161
  }
12072
12162
 
@@ -12153,6 +12243,50 @@ function setupUser(options) {
12153
12243
  }
12154
12244
  return deferred.promise;
12155
12245
  }
12246
+
12247
+ /**
12248
+ * Wiki Link for SDK params
12249
+ * https://github.com/comprodls/comprodls-sdk-js/wiki/04_AUTH-Adapter#getuserprofileparams
12250
+ */
12251
+ function deleteUserAccount(options) {
12252
+ var self = this;
12253
+ return new Promise(function(resolve, reject) {
12254
+
12255
+ if (options.ext_user_id && options.body) {
12256
+ //Passed all validations, Contruct API url
12257
+ var url = self.config.DEFAULT_HOSTS.AUTHEXTN +
12258
+ self.config.AUTHEXTN_API_URLS.deleteUserAccount;
12259
+ url = helpers.api.constructAPIUrl(url, {
12260
+ accountid: self.accountId,
12261
+ ext_user_id: options.ext_user_id,
12262
+ });
12263
+
12264
+ // Setup request
12265
+ var requestAPI = request.delete(url)
12266
+ .set('Content-Type', 'application/json')
12267
+ .set('Accept', 'application/json');
12268
+ if (self.traceid) { requestAPI.set('X-Amzn-Trace-Id', self.traceid); }
12269
+
12270
+ requestAPI
12271
+ .send(options.body)
12272
+ .agent(keepaliveAgent)
12273
+ .end(function(error, response) {
12274
+ if (error) {
12275
+ var err = new DLSError(helpers.errors.ERROR_TYPES.API_ERROR, error);
12276
+ reject(err);
12277
+ } else {
12278
+ resolve(response.body);
12279
+ }
12280
+ });
12281
+ } else {
12282
+ var err = {};
12283
+ err.description = 'Mandatory field \'ext_user_id\' or \'body\' in request options.';
12284
+ err.message = err.description;
12285
+ err = new DLSError(helpers.errors.ERROR_TYPES.SDK_ERROR, err);
12286
+ reject(err);
12287
+ }
12288
+ });
12289
+ }
12156
12290
 
12157
12291
  },{"../../helpers":3,"agentkeepalive":31,"q":36,"superagent":39}],25:[function(require,module,exports){
12158
12292
  /*************************************************************************
@@ -12184,6 +12318,7 @@ var q = require('q');
12184
12318
  var request = require('superagent');
12185
12319
 
12186
12320
  var helpers = require('../../helpers');
12321
+ var requestLayer = require('../../helpers/lib/requestLayer');
12187
12322
 
12188
12323
  var DLSError = helpers.errors.DLSError;
12189
12324
 
@@ -12205,34 +12340,32 @@ function superuser(accountId) {
12205
12340
  */
12206
12341
  function getAllInstitutions(options) {
12207
12342
  var self = this;
12208
- // Initializing promise
12209
- var dfd = q.defer();
12210
12343
 
12211
- var url = self.config.DEFAULT_HOSTS.AUTH +
12212
- self.config.AUTH_API_URLS.getAllInstitutions;
12213
- url = helpers.api.constructAPIUrl(url, { accountid : self.accountId });
12344
+ var url = helpers.api.constructAPIUrl(
12345
+ self.config.DEFAULT_HOSTS.AUTH + self.config.AUTH_API_URLS.getAllInstitutions,
12346
+ { accountid : self.accountId }
12347
+ );
12214
12348
 
12215
12349
  var params = {};
12216
- if(options) {
12217
- if(options.lookup) { params.lookup = options.lookup; }
12218
- if(options.cursor) { params.cursor = options.cursor; }
12219
- if(options.limit) { params.limit = options.limit; }
12350
+ if (options) {
12351
+ if (options.lookup) { params.lookup = options.lookup; }
12352
+ if (options.cursor) { params.cursor = options.cursor; }
12353
+ if (options.start) { params.start = options.start; }
12354
+ if (options.end) { params.end = options.end; }
12220
12355
  }
12221
12356
 
12222
- //Setup request with URL and Params
12223
- var requestAPI = request.get(url).query(params);
12224
- if(self.traceid) { requestAPI.set('X-Amzn-Trace-Id', self.traceid); }
12225
-
12226
- requestAPI.end(function(err, response) {
12227
- if(err) {
12228
- err = new DLSError(helpers.errors.ERROR_TYPES.API_ERROR, err);
12229
- dfd.reject(err);
12230
- } else {
12231
- dfd.resolve(response.body);
12232
- }
12357
+ // Prepare request parameters & execute request
12358
+ var reqOptions = {
12359
+ params: params,
12360
+ headers: { traceid: self.traceid }
12361
+ };
12362
+ return requestLayer.get(url, reqOptions)
12363
+ .then(function (response) {
12364
+ return response.body;
12365
+ })
12366
+ .catch(function (err) {
12367
+ throw new DLSError(helpers.errors.ERROR_TYPES.API_ERROR, err);
12233
12368
  });
12234
-
12235
- return dfd.promise;
12236
12369
  }
12237
12370
 
12238
12371
  /**
@@ -12316,7 +12449,7 @@ function provisionSpacesToSuperAdmin(options) {
12316
12449
  return dfd.promise;
12317
12450
  }
12318
12451
 
12319
- },{"../../helpers":3,"q":36,"superagent":39}],26:[function(require,module,exports){
12452
+ },{"../../helpers":3,"../../helpers/lib/requestLayer":7,"q":36,"superagent":39}],26:[function(require,module,exports){
12320
12453
  /*************************************************************************
12321
12454
  *
12322
12455
  * COMPRO CONFIDENTIAL
@@ -18108,1093 +18241,5 @@ exports.cleanHeader = function(header, changesOrigin){
18108
18241
  return header;
18109
18242
  };
18110
18243
 
18111
- },{}],44:[function(require,module,exports){
18112
- /*!
18113
- * validate.js 0.9.0
18114
- *
18115
- * (c) 2013-2015 Nicklas Ansman, 2013 Wrapp
18116
- * Validate.js may be freely distributed under the MIT license.
18117
- * For all details and documentation:
18118
- * http://validatejs.org/
18119
- */
18120
-
18121
- (function(exports, module, define) {
18122
- "use strict";
18123
-
18124
- // The main function that calls the validators specified by the constraints.
18125
- // The options are the following:
18126
- // - format (string) - An option that controls how the returned value is formatted
18127
- // * flat - Returns a flat array of just the error messages
18128
- // * grouped - Returns the messages grouped by attribute (default)
18129
- // * detailed - Returns an array of the raw validation data
18130
- // - fullMessages (boolean) - If `true` (default) the attribute name is prepended to the error.
18131
- //
18132
- // Please note that the options are also passed to each validator.
18133
- var validate = function(attributes, constraints, options) {
18134
- options = v.extend({}, v.options, options);
18135
-
18136
- var results = v.runValidations(attributes, constraints, options)
18137
- , attr
18138
- , validator;
18139
-
18140
- for (attr in results) {
18141
- for (validator in results[attr]) {
18142
- if (v.isPromise(results[attr][validator])) {
18143
- throw new Error("Use validate.async if you want support for promises");
18144
- }
18145
- }
18146
- }
18147
- return validate.processValidationResults(results, options);
18148
- };
18149
-
18150
- var v = validate;
18151
-
18152
- // Copies over attributes from one or more sources to a single destination.
18153
- // Very much similar to underscore's extend.
18154
- // The first argument is the target object and the remaining arguments will be
18155
- // used as sources.
18156
- v.extend = function(obj) {
18157
- [].slice.call(arguments, 1).forEach(function(source) {
18158
- for (var attr in source) {
18159
- obj[attr] = source[attr];
18160
- }
18161
- });
18162
- return obj;
18163
- };
18164
-
18165
- v.extend(validate, {
18166
- // This is the version of the library as a semver.
18167
- // The toString function will allow it to be coerced into a string
18168
- version: {
18169
- major: 0,
18170
- minor: 9,
18171
- patch: 0,
18172
- metadata: null,
18173
- toString: function() {
18174
- var version = v.format("%{major}.%{minor}.%{patch}", v.version);
18175
- if (!v.isEmpty(v.version.metadata)) {
18176
- version += "+" + v.version.metadata;
18177
- }
18178
- return version;
18179
- }
18180
- },
18181
-
18182
- // Below is the dependencies that are used in validate.js
18183
-
18184
- // The constructor of the Promise implementation.
18185
- // If you are using Q.js, RSVP or any other A+ compatible implementation
18186
- // override this attribute to be the constructor of that promise.
18187
- // Since jQuery promises aren't A+ compatible they won't work.
18188
- Promise: typeof Promise !== "undefined" ? Promise : /* istanbul ignore next */ null,
18189
-
18190
- EMPTY_STRING_REGEXP: /^\s*$/,
18191
-
18192
- // Runs the validators specified by the constraints object.
18193
- // Will return an array of the format:
18194
- // [{attribute: "<attribute name>", error: "<validation result>"}, ...]
18195
- runValidations: function(attributes, constraints, options) {
18196
- var results = []
18197
- , attr
18198
- , validatorName
18199
- , value
18200
- , validators
18201
- , validator
18202
- , validatorOptions
18203
- , error;
18204
-
18205
- if (v.isDomElement(attributes) || v.isJqueryElement(attributes)) {
18206
- attributes = v.collectFormValues(attributes);
18207
- }
18208
-
18209
- // Loops through each constraints, finds the correct validator and run it.
18210
- for (attr in constraints) {
18211
- value = v.getDeepObjectValue(attributes, attr);
18212
- // This allows the constraints for an attribute to be a function.
18213
- // The function will be called with the value, attribute name, the complete dict of
18214
- // attributes as well as the options and constraints passed in.
18215
- // This is useful when you want to have different
18216
- // validations depending on the attribute value.
18217
- validators = v.result(constraints[attr], value, attributes, attr, options, constraints);
18218
-
18219
- for (validatorName in validators) {
18220
- validator = v.validators[validatorName];
18221
-
18222
- if (!validator) {
18223
- error = v.format("Unknown validator %{name}", {name: validatorName});
18224
- throw new Error(error);
18225
- }
18226
-
18227
- validatorOptions = validators[validatorName];
18228
- // This allows the options to be a function. The function will be
18229
- // called with the value, attribute name, the complete dict of
18230
- // attributes as well as the options and constraints passed in.
18231
- // This is useful when you want to have different
18232
- // validations depending on the attribute value.
18233
- validatorOptions = v.result(validatorOptions, value, attributes, attr, options, constraints);
18234
- if (!validatorOptions) {
18235
- continue;
18236
- }
18237
- results.push({
18238
- attribute: attr,
18239
- value: value,
18240
- validator: validatorName,
18241
- globalOptions: options,
18242
- attributes: attributes,
18243
- options: validatorOptions,
18244
- error: validator.call(validator,
18245
- value,
18246
- validatorOptions,
18247
- attr,
18248
- attributes,
18249
- options)
18250
- });
18251
- }
18252
- }
18253
-
18254
- return results;
18255
- },
18256
-
18257
- // Takes the output from runValidations and converts it to the correct
18258
- // output format.
18259
- processValidationResults: function(errors, options) {
18260
- var attr;
18261
-
18262
- errors = v.pruneEmptyErrors(errors, options);
18263
- errors = v.expandMultipleErrors(errors, options);
18264
- errors = v.convertErrorMessages(errors, options);
18265
-
18266
- switch (options.format || "grouped") {
18267
- case "detailed":
18268
- // Do nothing more to the errors
18269
- break;
18270
-
18271
- case "flat":
18272
- errors = v.flattenErrorsToArray(errors);
18273
- break;
18274
-
18275
- case "grouped":
18276
- errors = v.groupErrorsByAttribute(errors);
18277
- for (attr in errors) {
18278
- errors[attr] = v.flattenErrorsToArray(errors[attr]);
18279
- }
18280
- break;
18281
-
18282
- default:
18283
- throw new Error(v.format("Unknown format %{format}", options));
18284
- }
18285
-
18286
- return v.isEmpty(errors) ? undefined : errors;
18287
- },
18288
-
18289
- // Runs the validations with support for promises.
18290
- // This function will return a promise that is settled when all the
18291
- // validation promises have been completed.
18292
- // It can be called even if no validations returned a promise.
18293
- async: function(attributes, constraints, options) {
18294
- options = v.extend({}, v.async.options, options);
18295
-
18296
- var WrapErrors = options.wrapErrors || function(errors) {
18297
- return errors;
18298
- };
18299
-
18300
- // Removes unknown attributes
18301
- if (options.cleanAttributes !== false) {
18302
- attributes = v.cleanAttributes(attributes, constraints);
18303
- }
18304
-
18305
- var results = v.runValidations(attributes, constraints, options);
18306
-
18307
- return new v.Promise(function(resolve, reject) {
18308
- v.waitForResults(results).then(function() {
18309
- var errors = v.processValidationResults(results, options);
18310
- if (errors) {
18311
- reject(new WrapErrors(errors, options, attributes, constraints));
18312
- } else {
18313
- resolve(attributes);
18314
- }
18315
- }, function(err) {
18316
- reject(err);
18317
- });
18318
- });
18319
- },
18320
-
18321
- single: function(value, constraints, options) {
18322
- options = v.extend({}, v.single.options, options, {
18323
- format: "flat",
18324
- fullMessages: false
18325
- });
18326
- return v({single: value}, {single: constraints}, options);
18327
- },
18328
-
18329
- // Returns a promise that is resolved when all promises in the results array
18330
- // are settled. The promise returned from this function is always resolved,
18331
- // never rejected.
18332
- // This function modifies the input argument, it replaces the promises
18333
- // with the value returned from the promise.
18334
- waitForResults: function(results) {
18335
- // Create a sequence of all the results starting with a resolved promise.
18336
- return results.reduce(function(memo, result) {
18337
- // If this result isn't a promise skip it in the sequence.
18338
- if (!v.isPromise(result.error)) {
18339
- return memo;
18340
- }
18341
-
18342
- return memo.then(function() {
18343
- return result.error.then(
18344
- function(error) {
18345
- result.error = error || null;
18346
- },
18347
- function(error) {
18348
- if (error instanceof Error) {
18349
- throw error;
18350
- }
18351
- v.error("Rejecting promises with the result is deprecated. Please use the resolve callback instead.");
18352
- result.error = error;
18353
- }
18354
- );
18355
- });
18356
- }, new v.Promise(function(r) { r(); })); // A resolved promise
18357
- },
18358
-
18359
- // If the given argument is a call: function the and: function return the value
18360
- // otherwise just return the value. Additional arguments will be passed as
18361
- // arguments to the function.
18362
- // Example:
18363
- // ```
18364
- // result('foo') // 'foo'
18365
- // result(Math.max, 1, 2) // 2
18366
- // ```
18367
- result: function(value) {
18368
- var args = [].slice.call(arguments, 1);
18369
- if (typeof value === 'function') {
18370
- value = value.apply(null, args);
18371
- }
18372
- return value;
18373
- },
18374
-
18375
- // Checks if the value is a number. This function does not consider NaN a
18376
- // number like many other `isNumber` functions do.
18377
- isNumber: function(value) {
18378
- return typeof value === 'number' && !isNaN(value);
18379
- },
18380
-
18381
- // Returns false if the object is not a function
18382
- isFunction: function(value) {
18383
- return typeof value === 'function';
18384
- },
18385
-
18386
- // A simple check to verify that the value is an integer. Uses `isNumber`
18387
- // and a simple modulo check.
18388
- isInteger: function(value) {
18389
- return v.isNumber(value) && value % 1 === 0;
18390
- },
18391
-
18392
- // Uses the `Object` function to check if the given argument is an object.
18393
- isObject: function(obj) {
18394
- return obj === Object(obj);
18395
- },
18396
-
18397
- // Simply checks if the object is an instance of a date
18398
- isDate: function(obj) {
18399
- return obj instanceof Date;
18400
- },
18401
-
18402
- // Returns false if the object is `null` of `undefined`
18403
- isDefined: function(obj) {
18404
- return obj !== null && obj !== undefined;
18405
- },
18406
-
18407
- // Checks if the given argument is a promise. Anything with a `then`
18408
- // function is considered a promise.
18409
- isPromise: function(p) {
18410
- return !!p && v.isFunction(p.then);
18411
- },
18412
-
18413
- isJqueryElement: function(o) {
18414
- return o && v.isString(o.jquery);
18415
- },
18416
-
18417
- isDomElement: function(o) {
18418
- if (!o) {
18419
- return false;
18420
- }
18421
-
18422
- if (!v.isFunction(o.querySelectorAll) || !v.isFunction(o.querySelector)) {
18423
- return false;
18424
- }
18425
-
18426
- if (v.isObject(document) && o === document) {
18427
- return true;
18428
- }
18429
-
18430
- // http://stackoverflow.com/a/384380/699304
18431
- /* istanbul ignore else */
18432
- if (typeof HTMLElement === "object") {
18433
- return o instanceof HTMLElement;
18434
- } else {
18435
- return o &&
18436
- typeof o === "object" &&
18437
- o !== null &&
18438
- o.nodeType === 1 &&
18439
- typeof o.nodeName === "string";
18440
- }
18441
- },
18442
-
18443
- isEmpty: function(value) {
18444
- var attr;
18445
-
18446
- // Null and undefined are empty
18447
- if (!v.isDefined(value)) {
18448
- return true;
18449
- }
18450
-
18451
- // functions are non empty
18452
- if (v.isFunction(value)) {
18453
- return false;
18454
- }
18455
-
18456
- // Whitespace only strings are empty
18457
- if (v.isString(value)) {
18458
- return v.EMPTY_STRING_REGEXP.test(value);
18459
- }
18460
-
18461
- // For arrays we use the length property
18462
- if (v.isArray(value)) {
18463
- return value.length === 0;
18464
- }
18465
-
18466
- // Dates have no attributes but aren't empty
18467
- if (v.isDate(value)) {
18468
- return false;
18469
- }
18470
-
18471
- // If we find at least one property we consider it non empty
18472
- if (v.isObject(value)) {
18473
- for (attr in value) {
18474
- return false;
18475
- }
18476
- return true;
18477
- }
18478
-
18479
- return false;
18480
- },
18481
-
18482
- // Formats the specified strings with the given values like so:
18483
- // ```
18484
- // format("Foo: %{foo}", {foo: "bar"}) // "Foo bar"
18485
- // ```
18486
- // If you want to write %{...} without having it replaced simply
18487
- // prefix it with % like this `Foo: %%{foo}` and it will be returned
18488
- // as `"Foo: %{foo}"`
18489
- format: v.extend(function(str, vals) {
18490
- if (!v.isString(str)) {
18491
- return str;
18492
- }
18493
- return str.replace(v.format.FORMAT_REGEXP, function(m0, m1, m2) {
18494
- if (m1 === '%') {
18495
- return "%{" + m2 + "}";
18496
- } else {
18497
- return String(vals[m2]);
18498
- }
18499
- });
18500
- }, {
18501
- // Finds %{key} style patterns in the given string
18502
- FORMAT_REGEXP: /(%?)%\{([^\}]+)\}/g
18503
- }),
18504
-
18505
- // "Prettifies" the given string.
18506
- // Prettifying means replacing [.\_-] with spaces as well as splitting
18507
- // camel case words.
18508
- prettify: function(str) {
18509
- if (v.isNumber(str)) {
18510
- // If there are more than 2 decimals round it to two
18511
- if ((str * 100) % 1 === 0) {
18512
- return "" + str;
18513
- } else {
18514
- return parseFloat(Math.round(str * 100) / 100).toFixed(2);
18515
- }
18516
- }
18517
-
18518
- if (v.isArray(str)) {
18519
- return str.map(function(s) { return v.prettify(s); }).join(", ");
18520
- }
18521
-
18522
- if (v.isObject(str)) {
18523
- return str.toString();
18524
- }
18525
-
18526
- // Ensure the string is actually a string
18527
- str = "" + str;
18528
-
18529
- return str
18530
- // Splits keys separated by periods
18531
- .replace(/([^\s])\.([^\s])/g, '$1 $2')
18532
- // Removes backslashes
18533
- .replace(/\\+/g, '')
18534
- // Replaces - and - with space
18535
- .replace(/[_-]/g, ' ')
18536
- // Splits camel cased words
18537
- .replace(/([a-z])([A-Z])/g, function(m0, m1, m2) {
18538
- return "" + m1 + " " + m2.toLowerCase();
18539
- })
18540
- .toLowerCase();
18541
- },
18542
-
18543
- stringifyValue: function(value) {
18544
- return v.prettify(value);
18545
- },
18546
-
18547
- isString: function(value) {
18548
- return typeof value === 'string';
18549
- },
18550
-
18551
- isArray: function(value) {
18552
- return {}.toString.call(value) === '[object Array]';
18553
- },
18554
-
18555
- contains: function(obj, value) {
18556
- if (!v.isDefined(obj)) {
18557
- return false;
18558
- }
18559
- if (v.isArray(obj)) {
18560
- return obj.indexOf(value) !== -1;
18561
- }
18562
- return value in obj;
18563
- },
18564
-
18565
- forEachKeyInKeypath: function(object, keypath, callback) {
18566
- if (!v.isString(keypath)) {
18567
- return undefined;
18568
- }
18569
-
18570
- var key = ""
18571
- , i
18572
- , escape = false;
18573
-
18574
- for (i = 0; i < keypath.length; ++i) {
18575
- switch (keypath[i]) {
18576
- case '.':
18577
- if (escape) {
18578
- escape = false;
18579
- key += '.';
18580
- } else {
18581
- object = callback(object, key, false);
18582
- key = "";
18583
- }
18584
- break;
18585
-
18586
- case '\\':
18587
- if (escape) {
18588
- escape = false;
18589
- key += '\\';
18590
- } else {
18591
- escape = true;
18592
- }
18593
- break;
18594
-
18595
- default:
18596
- escape = false;
18597
- key += keypath[i];
18598
- break;
18599
- }
18600
- }
18601
-
18602
- return callback(object, key, true);
18603
- },
18604
-
18605
- getDeepObjectValue: function(obj, keypath) {
18606
- if (!v.isObject(obj)) {
18607
- return undefined;
18608
- }
18609
-
18610
- return v.forEachKeyInKeypath(obj, keypath, function(obj, key) {
18611
- if (v.isObject(obj)) {
18612
- return obj[key];
18613
- }
18614
- });
18615
- },
18616
-
18617
- // This returns an object with all the values of the form.
18618
- // It uses the input name as key and the value as value
18619
- // So for example this:
18620
- // <input type="text" name="email" value="foo@bar.com" />
18621
- // would return:
18622
- // {email: "foo@bar.com"}
18623
- collectFormValues: function(form, options) {
18624
- var values = {}
18625
- , i
18626
- , input
18627
- , inputs
18628
- , value;
18629
-
18630
- if (v.isJqueryElement(form)) {
18631
- form = form[0];
18632
- }
18633
-
18634
- if (!form) {
18635
- return values;
18636
- }
18637
-
18638
- options = options || {};
18639
-
18640
- inputs = form.querySelectorAll("input[name], textarea[name]");
18641
- for (i = 0; i < inputs.length; ++i) {
18642
- input = inputs.item(i);
18643
-
18644
- if (v.isDefined(input.getAttribute("data-ignored"))) {
18645
- continue;
18646
- }
18647
-
18648
- value = v.sanitizeFormValue(input.value, options);
18649
- if (input.type === "number") {
18650
- value = value ? +value : null;
18651
- } else if (input.type === "checkbox") {
18652
- if (input.attributes.value) {
18653
- if (!input.checked) {
18654
- value = values[input.name] || null;
18655
- }
18656
- } else {
18657
- value = input.checked;
18658
- }
18659
- } else if (input.type === "radio") {
18660
- if (!input.checked) {
18661
- value = values[input.name] || null;
18662
- }
18663
- }
18664
- values[input.name] = value;
18665
- }
18666
-
18667
- inputs = form.querySelectorAll("select[name]");
18668
- for (i = 0; i < inputs.length; ++i) {
18669
- input = inputs.item(i);
18670
- value = v.sanitizeFormValue(input.options[input.selectedIndex].value, options);
18671
- values[input.name] = value;
18672
- }
18673
-
18674
- return values;
18675
- },
18676
-
18677
- sanitizeFormValue: function(value, options) {
18678
- if (options.trim && v.isString(value)) {
18679
- value = value.trim();
18680
- }
18681
-
18682
- if (options.nullify !== false && value === "") {
18683
- return null;
18684
- }
18685
- return value;
18686
- },
18687
-
18688
- capitalize: function(str) {
18689
- if (!v.isString(str)) {
18690
- return str;
18691
- }
18692
- return str[0].toUpperCase() + str.slice(1);
18693
- },
18694
-
18695
- // Remove all errors who's error attribute is empty (null or undefined)
18696
- pruneEmptyErrors: function(errors) {
18697
- return errors.filter(function(error) {
18698
- return !v.isEmpty(error.error);
18699
- });
18700
- },
18701
-
18702
- // In
18703
- // [{error: ["err1", "err2"], ...}]
18704
- // Out
18705
- // [{error: "err1", ...}, {error: "err2", ...}]
18706
- //
18707
- // All attributes in an error with multiple messages are duplicated
18708
- // when expanding the errors.
18709
- expandMultipleErrors: function(errors) {
18710
- var ret = [];
18711
- errors.forEach(function(error) {
18712
- // Removes errors without a message
18713
- if (v.isArray(error.error)) {
18714
- error.error.forEach(function(msg) {
18715
- ret.push(v.extend({}, error, {error: msg}));
18716
- });
18717
- } else {
18718
- ret.push(error);
18719
- }
18720
- });
18721
- return ret;
18722
- },
18723
-
18724
- // Converts the error mesages by prepending the attribute name unless the
18725
- // message is prefixed by ^
18726
- convertErrorMessages: function(errors, options) {
18727
- options = options || {};
18728
-
18729
- var ret = [];
18730
- errors.forEach(function(errorInfo) {
18731
- var error = v.result(errorInfo.error,
18732
- errorInfo.value,
18733
- errorInfo.attribute,
18734
- errorInfo.options,
18735
- errorInfo.attributes,
18736
- errorInfo.globalOptions);
18737
-
18738
- if (!v.isString(error)) {
18739
- ret.push(errorInfo);
18740
- return;
18741
- }
18742
-
18743
- if (error[0] === '^') {
18744
- error = error.slice(1);
18745
- } else if (options.fullMessages !== false) {
18746
- error = v.capitalize(v.prettify(errorInfo.attribute)) + " " + error;
18747
- }
18748
- error = error.replace(/\\\^/g, "^");
18749
- error = v.format(error, {value: v.stringifyValue(errorInfo.value)});
18750
- ret.push(v.extend({}, errorInfo, {error: error}));
18751
- });
18752
- return ret;
18753
- },
18754
-
18755
- // In:
18756
- // [{attribute: "<attributeName>", ...}]
18757
- // Out:
18758
- // {"<attributeName>": [{attribute: "<attributeName>", ...}]}
18759
- groupErrorsByAttribute: function(errors) {
18760
- var ret = {};
18761
- errors.forEach(function(error) {
18762
- var list = ret[error.attribute];
18763
- if (list) {
18764
- list.push(error);
18765
- } else {
18766
- ret[error.attribute] = [error];
18767
- }
18768
- });
18769
- return ret;
18770
- },
18771
-
18772
- // In:
18773
- // [{error: "<message 1>", ...}, {error: "<message 2>", ...}]
18774
- // Out:
18775
- // ["<message 1>", "<message 2>"]
18776
- flattenErrorsToArray: function(errors) {
18777
- return errors.map(function(error) { return error.error; });
18778
- },
18779
-
18780
- cleanAttributes: function(attributes, whitelist) {
18781
- function whitelistCreator(obj, key, last) {
18782
- if (v.isObject(obj[key])) {
18783
- return obj[key];
18784
- }
18785
- return (obj[key] = last ? true : {});
18786
- }
18787
-
18788
- function buildObjectWhitelist(whitelist) {
18789
- var ow = {}
18790
- , lastObject
18791
- , attr;
18792
- for (attr in whitelist) {
18793
- if (!whitelist[attr]) {
18794
- continue;
18795
- }
18796
- v.forEachKeyInKeypath(ow, attr, whitelistCreator);
18797
- }
18798
- return ow;
18799
- }
18800
-
18801
- function cleanRecursive(attributes, whitelist) {
18802
- if (!v.isObject(attributes)) {
18803
- return attributes;
18804
- }
18805
-
18806
- var ret = v.extend({}, attributes)
18807
- , w
18808
- , attribute;
18809
-
18810
- for (attribute in attributes) {
18811
- w = whitelist[attribute];
18812
-
18813
- if (v.isObject(w)) {
18814
- ret[attribute] = cleanRecursive(ret[attribute], w);
18815
- } else if (!w) {
18816
- delete ret[attribute];
18817
- }
18818
- }
18819
- return ret;
18820
- }
18821
-
18822
- if (!v.isObject(whitelist) || !v.isObject(attributes)) {
18823
- return {};
18824
- }
18825
-
18826
- whitelist = buildObjectWhitelist(whitelist);
18827
- return cleanRecursive(attributes, whitelist);
18828
- },
18829
-
18830
- exposeModule: function(validate, root, exports, module, define) {
18831
- if (exports) {
18832
- if (module && module.exports) {
18833
- exports = module.exports = validate;
18834
- }
18835
- exports.validate = validate;
18836
- } else {
18837
- root.validate = validate;
18838
- if (validate.isFunction(define) && define.amd) {
18839
- define([], function () { return validate; });
18840
- }
18841
- }
18842
- },
18843
-
18844
- warn: function(msg) {
18845
- if (typeof console !== "undefined" && console.warn) {
18846
- console.warn("[validate.js] " + msg);
18847
- }
18848
- },
18849
-
18850
- error: function(msg) {
18851
- if (typeof console !== "undefined" && console.error) {
18852
- console.error("[validate.js] " + msg);
18853
- }
18854
- }
18855
- });
18856
-
18857
- validate.validators = {
18858
- // Presence validates that the value isn't empty
18859
- presence: function(value, options) {
18860
- options = v.extend({}, this.options, options);
18861
- if (v.isEmpty(value)) {
18862
- return options.message || this.message || "can't be blank";
18863
- }
18864
- },
18865
- length: function(value, options, attribute) {
18866
- // Empty values are allowed
18867
- if (v.isEmpty(value)) {
18868
- return;
18869
- }
18870
-
18871
- options = v.extend({}, this.options, options);
18872
-
18873
- var is = options.is
18874
- , maximum = options.maximum
18875
- , minimum = options.minimum
18876
- , tokenizer = options.tokenizer || function(val) { return val; }
18877
- , err
18878
- , errors = [];
18879
-
18880
- value = tokenizer(value);
18881
- var length = value.length;
18882
- if(!v.isNumber(length)) {
18883
- v.error(v.format("Attribute %{attr} has a non numeric value for `length`", {attr: attribute}));
18884
- return options.message || this.notValid || "has an incorrect length";
18885
- }
18886
-
18887
- // Is checks
18888
- if (v.isNumber(is) && length !== is) {
18889
- err = options.wrongLength ||
18890
- this.wrongLength ||
18891
- "is the wrong length (should be %{count} characters)";
18892
- errors.push(v.format(err, {count: is}));
18893
- }
18894
-
18895
- if (v.isNumber(minimum) && length < minimum) {
18896
- err = options.tooShort ||
18897
- this.tooShort ||
18898
- "is too short (minimum is %{count} characters)";
18899
- errors.push(v.format(err, {count: minimum}));
18900
- }
18901
-
18902
- if (v.isNumber(maximum) && length > maximum) {
18903
- err = options.tooLong ||
18904
- this.tooLong ||
18905
- "is too long (maximum is %{count} characters)";
18906
- errors.push(v.format(err, {count: maximum}));
18907
- }
18908
-
18909
- if (errors.length > 0) {
18910
- return options.message || errors;
18911
- }
18912
- },
18913
- numericality: function(value, options) {
18914
- // Empty values are fine
18915
- if (v.isEmpty(value)) {
18916
- return;
18917
- }
18918
-
18919
- options = v.extend({}, this.options, options);
18920
-
18921
- var errors = []
18922
- , name
18923
- , count
18924
- , checks = {
18925
- greaterThan: function(v, c) { return v > c; },
18926
- greaterThanOrEqualTo: function(v, c) { return v >= c; },
18927
- equalTo: function(v, c) { return v === c; },
18928
- lessThan: function(v, c) { return v < c; },
18929
- lessThanOrEqualTo: function(v, c) { return v <= c; }
18930
- };
18931
-
18932
- // Coerce the value to a number unless we're being strict.
18933
- if (options.noStrings !== true && v.isString(value)) {
18934
- value = +value;
18935
- }
18936
-
18937
- // If it's not a number we shouldn't continue since it will compare it.
18938
- if (!v.isNumber(value)) {
18939
- return options.message || options.notValid || this.notValid || "is not a number";
18940
- }
18941
-
18942
- // Same logic as above, sort of. Don't bother with comparisons if this
18943
- // doesn't pass.
18944
- if (options.onlyInteger && !v.isInteger(value)) {
18945
- return options.message || options.notInteger || this.notInteger || "must be an integer";
18946
- }
18947
-
18948
- for (name in checks) {
18949
- count = options[name];
18950
- if (v.isNumber(count) && !checks[name](value, count)) {
18951
- // This picks the default message if specified
18952
- // For example the greaterThan check uses the message from
18953
- // this.notGreaterThan so we capitalize the name and prepend "not"
18954
- var key = "not" + v.capitalize(name);
18955
- var msg = options[key] || this[key] || "must be %{type} %{count}";
18956
-
18957
- errors.push(v.format(msg, {
18958
- count: count,
18959
- type: v.prettify(name)
18960
- }));
18961
- }
18962
- }
18963
-
18964
- if (options.odd && value % 2 !== 1) {
18965
- errors.push(options.notOdd || this.notOdd || "must be odd");
18966
- }
18967
- if (options.even && value % 2 !== 0) {
18968
- errors.push(options.notEven || this.notEven || "must be even");
18969
- }
18970
-
18971
- if (errors.length) {
18972
- return options.message || errors;
18973
- }
18974
- },
18975
- datetime: v.extend(function(value, options) {
18976
- if (!v.isFunction(this.parse) || !v.isFunction(this.format)) {
18977
- throw new Error("Both the parse and format functions needs to be set to use the datetime/date validator");
18978
- }
18979
-
18980
- // Empty values are fine
18981
- if (v.isEmpty(value)) {
18982
- return;
18983
- }
18984
-
18985
- options = v.extend({}, this.options, options);
18986
-
18987
- var err
18988
- , errors = []
18989
- , earliest = options.earliest ? this.parse(options.earliest, options) : NaN
18990
- , latest = options.latest ? this.parse(options.latest, options) : NaN;
18991
-
18992
- value = this.parse(value, options);
18993
-
18994
- // 86400000 is the number of seconds in a day, this is used to remove
18995
- // the time from the date
18996
- if (isNaN(value) || options.dateOnly && value % 86400000 !== 0) {
18997
- return options.message || this.notValid || "must be a valid date";
18998
- }
18999
-
19000
- if (!isNaN(earliest) && value < earliest) {
19001
- err = this.tooEarly || "must be no earlier than %{date}";
19002
- err = v.format(err, {date: this.format(earliest, options)});
19003
- errors.push(err);
19004
- }
19005
-
19006
- if (!isNaN(latest) && value > latest) {
19007
- err = this.tooLate || "must be no later than %{date}";
19008
- err = v.format(err, {date: this.format(latest, options)});
19009
- errors.push(err);
19010
- }
19011
-
19012
- if (errors.length) {
19013
- return options.message || errors;
19014
- }
19015
- }, {
19016
- parse: null,
19017
- format: null
19018
- }),
19019
- date: function(value, options) {
19020
- options = v.extend({}, options, {dateOnly: true});
19021
- return v.validators.datetime.call(v.validators.datetime, value, options);
19022
- },
19023
- format: function(value, options) {
19024
- if (v.isString(options) || (options instanceof RegExp)) {
19025
- options = {pattern: options};
19026
- }
19027
-
19028
- options = v.extend({}, this.options, options);
19029
-
19030
- var message = options.message || this.message || "is invalid"
19031
- , pattern = options.pattern
19032
- , match;
19033
-
19034
- // Empty values are allowed
19035
- if (v.isEmpty(value)) {
19036
- return;
19037
- }
19038
- if (!v.isString(value)) {
19039
- return message;
19040
- }
19041
-
19042
- if (v.isString(pattern)) {
19043
- pattern = new RegExp(options.pattern, options.flags);
19044
- }
19045
- match = pattern.exec(value);
19046
- if (!match || match[0].length != value.length) {
19047
- return message;
19048
- }
19049
- },
19050
- inclusion: function(value, options) {
19051
- // Empty values are fine
19052
- if (v.isEmpty(value)) {
19053
- return;
19054
- }
19055
- if (v.isArray(options)) {
19056
- options = {within: options};
19057
- }
19058
- options = v.extend({}, this.options, options);
19059
- if (v.contains(options.within, value)) {
19060
- return;
19061
- }
19062
- var message = options.message ||
19063
- this.message ||
19064
- "^%{value} is not included in the list";
19065
- return v.format(message, {value: value});
19066
- },
19067
- exclusion: function(value, options) {
19068
- // Empty values are fine
19069
- if (v.isEmpty(value)) {
19070
- return;
19071
- }
19072
- if (v.isArray(options)) {
19073
- options = {within: options};
19074
- }
19075
- options = v.extend({}, this.options, options);
19076
- if (!v.contains(options.within, value)) {
19077
- return;
19078
- }
19079
- var message = options.message || this.message || "^%{value} is restricted";
19080
- return v.format(message, {value: value});
19081
- },
19082
- email: v.extend(function(value, options) {
19083
- options = v.extend({}, this.options, options);
19084
- var message = options.message || this.message || "is not a valid email";
19085
- // Empty values are fine
19086
- if (v.isEmpty(value)) {
19087
- return;
19088
- }
19089
- if (!v.isString(value)) {
19090
- return message;
19091
- }
19092
- if (!this.PATTERN.exec(value)) {
19093
- return message;
19094
- }
19095
- }, {
19096
- PATTERN: /^[a-z0-9\u007F-\uffff!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9\u007F-\uffff!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/i
19097
- }),
19098
- equality: function(value, options, attribute, attributes) {
19099
- if (v.isEmpty(value)) {
19100
- return;
19101
- }
19102
-
19103
- if (v.isString(options)) {
19104
- options = {attribute: options};
19105
- }
19106
- options = v.extend({}, this.options, options);
19107
- var message = options.message ||
19108
- this.message ||
19109
- "is not equal to %{attribute}";
19110
-
19111
- if (v.isEmpty(options.attribute) || !v.isString(options.attribute)) {
19112
- throw new Error("The attribute must be a non empty string");
19113
- }
19114
-
19115
- var otherValue = v.getDeepObjectValue(attributes, options.attribute)
19116
- , comparator = options.comparator || function(v1, v2) {
19117
- return v1 === v2;
19118
- };
19119
-
19120
- if (!comparator(value, otherValue, options, attribute, attributes)) {
19121
- return v.format(message, {attribute: v.prettify(options.attribute)});
19122
- }
19123
- },
19124
-
19125
- // A URL validator that is used to validate URLs with the ability to
19126
- // restrict schemes and some domains.
19127
- url: function(value, options) {
19128
- if (v.isEmpty(value)) {
19129
- return;
19130
- }
19131
-
19132
- options = v.extend({}, this.options, options);
19133
-
19134
- var message = options.message || this.message || "is not a valid url"
19135
- , schemes = options.schemes || this.schemes || ['http', 'https']
19136
- , allowLocal = options.allowLocal || this.allowLocal || false;
19137
-
19138
- if (!v.isString(value)) {
19139
- return message;
19140
- }
19141
-
19142
- // https://gist.github.com/dperini/729294
19143
- var regex =
19144
- "^" +
19145
- // schemes
19146
- "(?:(?:" + schemes.join("|") + "):\\/\\/)" +
19147
- // credentials
19148
- "(?:\\S+(?::\\S*)?@)?";
19149
-
19150
- regex += "(?:";
19151
-
19152
- var hostname =
19153
- "(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)" +
19154
- "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*" +
19155
- "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))";
19156
-
19157
- // This ia a special case for the localhost hostname
19158
- if (allowLocal) {
19159
- hostname = "(?:localhost|" + hostname + ")";
19160
- } else {
19161
- // private & local addresses
19162
- regex +=
19163
- "(?!10(?:\\.\\d{1,3}){3})" +
19164
- "(?!127(?:\\.\\d{1,3}){3})" +
19165
- "(?!169\\.254(?:\\.\\d{1,3}){2})" +
19166
- "(?!192\\.168(?:\\.\\d{1,3}){2})" +
19167
- "(?!172" +
19168
- "\\.(?:1[6-9]|2\\d|3[0-1])" +
19169
- "(?:\\.\\d{1,3})" +
19170
- "{2})";
19171
- }
19172
-
19173
- // reserved addresses
19174
- regex +=
19175
- "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
19176
- "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
19177
- "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
19178
- "|" +
19179
- hostname +
19180
- // port number
19181
- "(?::\\d{2,5})?" +
19182
- // path
19183
- "(?:\\/[^\\s]*)?" +
19184
- "$";
19185
-
19186
- var PATTERN = new RegExp(regex, 'i');
19187
- if (!PATTERN.exec(value)) {
19188
- return message;
19189
- }
19190
- }
19191
- };
19192
-
19193
- validate.exposeModule(validate, this, exports, module, define);
19194
- }).call(this,
19195
- typeof exports !== 'undefined' ? /* istanbul ignore next */ exports : null,
19196
- typeof module !== 'undefined' ? /* istanbul ignore next */ module : null,
19197
- typeof define !== 'undefined' ? /* istanbul ignore next */ define : null);
19198
-
19199
18244
  },{}]},{},[1])(1)
19200
18245
  });