/** * Validate a given attribute against a rule. * * @param string $attribute * @param string $rule * @return void */ protected function validate($attribute, $rule) { list($rule, $parameters) = $this->parseRule($rule);
if ($rule == '') return;
// We will get the value for the given attribute from the array of data and then
// verify that the attribute is indeed validatable. Unless the rule implies
// that the attribute is required, rules are not run for missing values.
$value = $this->getValue($attribute);
$validatable = $this->isValidatable($rule, $attribute, $value);
$method = "validate{$rule}";
$invoke = $this->$method($attribute, $value, $parameters, $this);
// If a validation of array mesage then the insertion of error message
// need to be customized
if (substr($method, -7) == 'OrArray')
{
if ($validatable && count($invoke) > 0)
{
$this->addArrayFailure($attribute, $rule, $parameters, $invoke);
}
}
else
{
if ($validatable && ! $invoke)
{
$this->addFailure($attribute, $rule, $parameters);
}
}
}
/**
* Get the validation message for an attribute and rule.
*
* @param string $attribute
* @param string $rule
* @return string
*/
protected function getMessage($attribute, $rule)
{
if (substr($rule, -7) == 'OrArray')
{
$rule = substr($rule, 0, -7);
}
return parent::getMessage($attribute, $rule);
}
/**
* Add a failed rule and error message of an array validation to the collection.
*
* @param string $attribute
* @param string $rule
* @param array $parameters
* @return void
*/
protected function addArrayFailure($attribute, $rule, $parameters, $positions)
{
// Insert default error, so user can use MessageBag
// {{ $errors->first('attribute', '<span>:message</span>') }}
// like always is
$this->addError($attribute, $rule, $parameters);
$this->failedRules[$attribute][$rule] = $parameters;
// Customized the error message to enhance the knowledge of
// at which point of the array, did the validation fails, hence
// instead of unknowingly detecting which one is false, now it will
// explicitly tell you at which position using array dot notation:
//
// {attribute}.{position} e.g.: telephone.1
//
foreach($positions as $position)
{
$this->addArrayError($attribute, $rule, $parameters, $position);
$this->failedRules[$attribute.'.'.$position][$rule] = $parameters;
}
}
/**
* Add an error message to the validator's collection of messages.
*
* @param string $attribute
* @param string $rule
* @param array $parameters
* @return void
*/
protected function addArrayError($attribute, $rule, $parameters, $position)
{
$message = $this->getMessage($attribute, $rule);
$message = $this->doReplacements($message, $attribute, $rule, $parameters);
$this->messages->add($attribute.'_'.$position, $message);
}