示例#1
0
 _onChangeField(refField){
     if(this.formClicked > 0){
         const value = this.refs[refField].getValue()
         const isValid = validate.single(value, this.formValidate[refField])
         this._triggerFieldError(isValid, refField)
     }
 }
	once: function (value, options, name) {
		var errors = [];
		var opts = [];
		var validationOpts = [];

		// Check if name was passed, determines which validate method to use
		if (name) {
			// Since name exists, use the main validate method but just pass one
			// property to it. Need to structure the objects it expects first.
			opts[name] = value;
			validationOpts[name] = processOptions(options);

			// Use main validate method, gives us better handling of custom messages
			// and key path name prepending.
			errors = validatejs(opts, validationOpts);

			// can.Map.define expects an array of strings, but main validate method
			// returns an object.
			if (errors) {
				errors = errors[name];
			}
		} else {
			errors = validatejs.single(value, processOptions(options));
		}

		return errors;
	},
示例#3
0
validate.validators.object = function(value) {
  if(value) {
    if(!validate.isObject(value)) {
      return "is not an object";
    }
  }
  return null;
}
示例#4
0
validate.validators.string = function(value) {
  if(value) {
    if(!validate.isString(value)) {
      return "is not a string";
    }
  }
  return null;
}
        amount: function (value) {

          if (validate.isEmpty(value)) {
            return {
                presence: {
                    message: 'is required'
                }
            };
          }
          if (!validate.isNumber(value)) {
            return {
                format: 'must not contain invalid amount. Must be a number.'
            };
          }

          return null;
        }
示例#6
0
validate.validators.array = function(value) {
  if(value) {
    if(!validate.isArray(value)) {
      return "is not an array";
    }
  }
  return null;
}
示例#7
0
Validators.prototype.isObject = function (obj) {
    if (obj != null) {
        var val = validate.isObject(obj);
        if (!val) {
            return util.constructValidationMessage(val, "Type is not an object");
        }
    }
    return true;
};
示例#8
0
文件: grid.js 项目: imsnif/grid
function Grid (width, height, offset) {
  assert(validate.isInteger(width), `${width} is not an integer`)
  assert(validate.isInteger(height), `${height} is not an integer`)
  offset = offset || { x: 0, y: 0 }
  let state = {
    offset,
    width,
    height,
    panes: []
  }
  return Object.assign(
    state,
    paneAdder(state),
    paneGetter(state),
    paneRemover(state),
    paneChanger(state)
  )
}
示例#9
0
Validators.prototype.isFloat = function(obj) {
  if(typeof obj !== 'undefined' && obj !== null) {
    var val = validate.isNumber(obj);
    if (!val) {
      return util.constructValidationMessage(val, "Type is not a float");
    }
  }
  return true;
};
示例#10
0
 var mapped = _.map(err.errors, function(value, key) {
   if (validate.isArray(value)) {
     return value.map(function(errObj) {
       return this.create(status, errObj);
     });
   } else {
     return errorResponse.create(status, value);
   }
 });
示例#11
0
ErrorResponse.prototype.error = function(err) {
  var status = this.status(err);

  // Check for multiple errors and handle them
  if (err.hasOwnProperty('errors')) {
    var errors = [];
    if (validate.isObject(err.errors)) {
      /*
        {
          id: [err1, err2],
          name: ['blah', 'bar']
        }
      */
      var errorResponse = this;
      var mapped = _.map(err.errors, function(value, key) {
        if (validate.isArray(value)) {
          return value.map(function(errObj) {
            return this.create(status, errObj);
          });
        } else {
          return errorResponse.create(status, value);
        }
      });

      return {errors: mapped};
    } else if (validate.isArray(err.errors)) {
      /*
        ['error one', 'error two']
      */
      errs = value.map(function(errObj) {
        return this.create(status, errObj);
      });

      return {errors: errs};
    } 
  } else {
    var error = this.create(status, err);

    return {errors: [error]};
  }
  
  
}
示例#12
0
  validateField(field, value) {
    const validationField = {};
    validationField[field] = value;

    const validationRule = this.ruleForField(field);
    const error = validate.validate(validationField, validationRule);

    this.reconcileErrors(field, error);
    return error;
  }
示例#13
0
 validationPromise = validationPromise.then(function() {
   return validate.async(processor, processor.$validate).catch(function(errors) {
     validationErrors.push({
       processor: processor.name,
       package: processor.$package,
       errors: errors
     });
     log.error('Invalid property in "' + processor.name + '" (in "' + processor.$package + '" package)');
     log.error(errors);
   });
 });
示例#14
0
export function validateData(data) {
  let i;
  let entry;

  if (validate.isArray(data)) {
    for (i = 0; i < data.length; i++) {
      entry = data[i];
      if (!(validate.isArray(entry) || validate.isObject(entry))) {
        console.error('Each entry within the array passed ' +
                      'through table.appendRows must be an array or object.');
        return false;
      }
    }
  } else {
    console.error('table.appendRows must be passed an array.');
    return false;
  }

  return true;
}
示例#15
0
        metadata: function (value) {

          if (validate.isEmpty(value)) {
            return {
                presence: {
                    message: 'is required'
                }
            };
          }

          return null;
        },
示例#16
0
Validators.prototype.isInt32 = function(obj) {
  if(typeof obj !== 'undefined' && obj !== null) {
    var val = validate.isInteger(obj);
    if (!val) {
      return util.constructValidationMessage(val, "Type is not a date");
    }
    if(obj > 2147483647 || obj < -2147483647) {
      return util.constructValidationMessage(false, "Int Exceeds 32-bits");
    }

  }
  return true;
};
示例#17
0
 handleSubmit(ev) {

    console.log('handleSubmit');

    ev.preventDefault();

    var v = Validate.collectFormValues(this.refs.formUpdateProfile);

    var errors = Validate(this.refs.formUpdateProfile, this.getConstraints());

    this.setState({ errors });

    if (!errors) this.save();
  }
示例#18
0
                to: function (value, attributes, attributeName, options, constraints) {
                    if (validate.isEmpty(value)) {
                        return {
                            presence: {message: "is required"}
                        };
                    }

                    if (!validate.isArray(value) && !validate.isString(value)) {
                        return {
                            format: "must be a string or an array strings (phone numbers)"
                        };
                    }

                    if (validate.isString(value)) {
                        // TODO: Validate number format
                        let isInvalid = false;
                        if (isInvalid) {
                            return {
                                format: "must be a valid phone number"
                            };
                        }
                    }

                    if (validate.isArray(value)) {
                        let foundInvalid = false;
                        value.forEach(function (phone) {
                            // TODO: Validate number format
                        });
                        if (foundInvalid) {
                            return {
                                format: "must NOT contain invalid phone number"
                            }
                        }
                    }

                    return null;
                },
示例#19
0
  patch(req, next) {
    // validate the request and clean it
    var jsonErrors = this.request.validateResource(req);
    if (!_.isEmpty(jsonErrors)) {
      return next(
        jsonErrors,
        null
      );
    }

    return next(
      validate(req.body.data.attributes, patchConstraints), 
      validate.cleanAttributes(req.body.data.attributes, patchConstraints)
    ); 
  }
示例#20
0
文件: gateway.js 项目: camuthig/haros
  constructor (msg, errors) {
    super(msg, 500);

    if (!validate.isArray(errors)) {
      errors = [errors];
    }

    for (var err of errors) {
      if (!(err instanceof StatusError)) {
        throw new Error('errors can only contain StatusError types');
      }
    }

    this.status = errors[0].status;
    this.errors = errors;
  }
    return function (req, res, next) {

            //validate async function for input validation
        validate.async(req.body, validationConstrain, {
            format: "flat"
        }).then(function () {
            next();
        }, function (errors) {
            return res.send({
                success: true,
                message: errors[0]
            });

        });

    };
 validateInput(element) {
     validate.async(this.createObjectFromInputs(this.inputs), this.constraints || {}).then(
         success => {
             this.errors = {};
             this.showAllErrors();
         },
         function(errors) {
             if (errors instanceof Error) {
                 throw errors;
             } else {
                 this.errors = errors;
                 this.showErrorsForInput(element, this.errors[element.name]);
             }
         }.bind(this)
     );
 }
示例#23
0
        productName: function (value) {

          if (validate.isEmpty(value)) {
            return {
                presence: {
                    message: 'is required'
                }
            };
          }
          if (!(/\S/).test(value)) {
            return {
                format: 'must not contain invalid productName - eg. Space'
            };
          }

          return null;
        },
 handleSubmission() {
     validate.async(this.createObjectFromInputs(this.inputs), this.constraints || {}).then(
         function() {
             this.errors = {};
             this.showAllErrors();
             this.form.submit();
         }.bind(this),
         function(errors) {
             if (errors instanceof Error) {
                 throw errors;
             } else {
                 this.errors = errors;
                 this.showAllErrors();
             }
         }.bind(this)
     );
 }
示例#25
0
        phoneNumber: function (value) {

          if (validate.isEmpty(value)) {
            return {
              presence: {
                message: 'is required'
              }
            };
          }
          if (!(/^\+?\d+$/).test(value)) {
            return {
                format: 'must not contain invalid phone number'
            };
          }

          return null;
        },
function _adicionar($scope, $ionicPopup, tarefa) {
	validate
		.async(tarefa, TAREFA_VALIDATE)
		.then(function() {
			Tarefas.insert(tarefa);
			$scope.tarefa = {};
			Util.$apply();
		}, function (validationErrors) {
			var errors = [];
			_.each(validationErrors, function (field) {
				errors = errors.concat(field);
			});
			$ionicPopup.alert({
					title: 'ToDo App!',
					template: errors.join('<br>')
				});
		});
}
示例#27
0
文件: max-size.js 项目: imsnif/grid
function maxSize (pane, direction) {
  assert(validate.isObject(pane), `${pane} must be an object`)
  const grid = pane.grid
  const obstruction = grid.panes
    .filter(p => validate.isDefined(pane.id) && validate.isDefined(p.id)
      ? p.id !== pane.id
      : true
    )
    .map((sibling) => findObstruction(pane, sibling, direction))
    .filter(o => o)
    .sort((a, b) => {
      if (direction === 'up' || direction === 'left') {
        return (a < b ? 1 : -1)
      } else {
        return (a > b ? 1 : -1)
      }
    })[0]
  return buildRetParams(pane, grid, obstruction, direction)
}
示例#28
0
exports.validate = function(req, res, next, validate) {
    if (validate) {
        var constraints = {};
        var attributes = {};

        for (var i = 0; i < validate.length; i++) {
            attributes[validate[i].name] = req[validate[i].source][validate[i].name] || null;
            constraints[validate[i].name] = validate[i].rules;
        }

        valid.async(attributes, constraints)
        .then(function(result) {
            next();
        }, function(err) {
            res.send(400, {error: err });
        });
    } else {
        next();
    }
};
示例#29
0
  validate(target, propName) {
    if (target && propName) {
      let validator = { [propName]: { [this.name]: this.config } };
      let result;
      if (this.name == "async") {
        validate.async2.options = {cleanAttributes: false};
        result = validate.async2(target, this.config, null, propName)
      }
      else {
        result = validate(target, validator);
        if (result) {
          let error = cleanResult(result);
          result = Promise.resolve(new ValidationError(error));
        }
      }

      return result;
    }
    throw new Error('Invalid target or property name.');
  }
示例#30
0
function PaneWrapper (Wrappee, opts) {
  assert(validate.isInteger(opts.x), `${opts.x} is not an integer`)
  assert(validate.isInteger(opts.y), `${opts.y} is not an integer`)
  assert(validate.isInteger(opts.width), `${opts.width} is not an integer`)
  assert(validate.isInteger(opts.height), `${opts.height} is not an integer`)
  const offset = (opts.grid && opts.grid.offset) || { x: 0, y: 0 }
  const wrapped = getWrappedObject(Wrappee, opts, offset)
  if (typeof wrapped.setBounds === 'function') {
    const currentBounds = wrapped.getBounds()
    wrapped.setBounds(Object.assign({}, currentBounds, {
      x: opts.x + offset.x,
      y: opts.y + offset.y,
      width: opts.width,
      height: opts.height
    }))
  }
  if (!validate.isDefined(opts.id) && !validate.isDefined(wrapped.id)) {
    if (typeof wrapped.close === 'function') wrapped.close()
    throw new Error('id is not defined')
  }
  let state = {
    wrapped,
    grid: opts.grid,
    id: opts.id || wrapped.id,
    width: opts.width,
    height: opts.height,
    x: opts.x,
    y: opts.y
  }
  const emitter = new EventEmitter()
  return Object.assign(
    state,
    {
      on: emitter.on,
      once: emitter.once,
      emit: emitter.emit,
      removeListener: emitter.removeListener,
      removeAllListeners: emitter.removeAllListeners
      // TODO: rest of relevant emitter methods
    },
    sizeChanger(state),
    locationChanger(state),
    directionalResizer(state),
    destructor(state)
  )
}