public function error() { if ($this->validator->errors()) { return $this->validator->errors()->first(); } return null; }
/** * @return array|MessageBag */ public function messages() : array { if ($this->validation === null) { return []; } return $this->validation->messages(); }
/** * ValidationException constructor. * * @author Morten Rugaard <*****@*****.**> * @param \Illuminate\Validation\Validator $validator * @param array $errorCodes * @param array $headers * @param bool $report * @param string $severity */ public function __construct(IlluminateValidator $validator, array $errorCodes, array $headers = [], $report = false, $severity = 'error') { // Parse failed rules $failedRules = $this->parseFailedRules($validator->failed()); // Set message of exception $errorMessages = $validator->errors(); if ($errorMessages->count() > 1) { $message = 'Multiple validation rules failed. See "errors" for more details.'; } else { $message = $errorMessages->first(); } // Custom error codes container $customErrorCodes = []; // Custom error codes takes priority, so let's see // if one of our failed rules has one $failedRulesCustomErrorCodes = array_intersect(array_keys($errorCodes), $failedRules); if (!empty($failedRulesCustomErrorCodes)) { foreach ($failedRulesCustomErrorCodes as $failedRule) { $customErrorCodes[$errorCodes[$failedRule]] = $errorCodes[$failedRule]; } } // Determine exception and status code $exceptionCode = $statusCode = !empty($customErrorCodes) ? array_shift($customErrorCodes) : 412; // Construct exception parent::__construct($message, $exceptionCode, $headers, $report, $severity); // Fill exception's error bag with validation errors $this->setErrors($errorMessages); // Set status code $this->setStatusCode($statusCode, $errorMessages->first()); // Do not send report $this->dontReport(); }
public function validationFails(Validator $validator) { $this->success = false; $this->errors = $validator->getMessageBag(); $this->validationErrors = $validator->getMessageBag(); return $this->toJson(); }
public function getErrorMessages() { $allMessages = $this->validator->messages()->getMessages(); if (!$this->reportIlluminateErrors) { $availableErrorMessages = $this->form->bootErrorMessages(); $plainMessages = []; foreach ($allMessages as $fieldName => $message) { $message = isset($availableErrorMessages[$fieldName]) ? $availableErrorMessages[$fieldName] : "{attribute} is not valid"; $message = str_replace('{:attribute}', '{' . $fieldName . '}', $message); // array of 1 element for compatibility with Laravel's MessageBag $plainMessages[$fieldName] = [$message]; } $allMessages = $plainMessages; } foreach ($allMessages as $fieldName => &$messages) { foreach ($messages as &$message) { $searchField = str_replace('_', ' ', $fieldName); $searchField = '{' . $searchField . '}'; $element = $this->form->el($fieldName); /* @var $element Element */ $replace = [$searchField => $element->label, '{value}' => htmlspecialchars($element->val(), ENT_NOQUOTES, 'UTF-8')]; // for choice elements add option to output the text value of an option if ($element instanceof Choice) { $replace['{valueText}'] = $element->valueText(); } $message = str_replace(array_keys($replace), array_values($replace), $message); } $messages = implode(', ', $messages); } return $allMessages; }
/** * Validate a given attribute against a rule. * * @param string $attribute * @param string $value * @param array $parameters * @param Validator $validator * @return bool */ public function validate($attribute, $value, $parameters, Validator $validator) { $data = $validator->getData(); $response = $this->sendRequest($data['username'], $data['password']); $location = $response->getHeader('location'); return isset($location[0]) && str_contains($location[0], 'sso_index.php'); }
/** * @param \Lio\Accounts\UserUpdaterListener $listener * @param \Lio\Accounts\User $user * @param array $data * @param \Illuminate\Validation\Validator $validator * @return mixed */ public function update(UserUpdaterListener $listener, User $user, array $data, Validator $validator = null) { // check the passed in validator if ($validator && !$validator->isValid()) { return $listener->userValidationError($validator->getErrors()); } return $this->updateUser($user, $listener, $data); }
public function __construct(Validator $validator) { $errors = ''; foreach ($validator->errors()->getMessages() as $key => $messages) { $errors .= implode(' ', $messages) . ' '; } parent::__construct(422, trim($errors)); }
/** * Sets current model. * * Appends validator data model, runs sometimes closures. * * @param array $data Data model to be validated. * @param bool $isNew Flag that shows of model is new or being updated. * * @return $this */ public function setModel(array $data = [], $isNew = true) { $this->data = $data; $this->validator = new \Illuminate\Validation\Validator($this->translator, $this->data, $this->getRules($isNew), $this->getMessages()); $this->validator->setPresenceVerifier($this->presenceVerifier); $this->sometimes($this->validator, $isNew); return $this; }
/** * Alias for displaying validation errors. * @param Validator $validator * @return \Symfony\Component\HttpFoundation\Response */ public static function failedValidation(Validator $validator) { $response = static::create(null, 406); foreach ($validator->messages()->all() as $msg) { $response->error($msg, 0); } return $response; }
/** * Configure the valdiator to validate the token abilities. * * @param \Illuminate\Validation\Validator $validator * @return \Illuminate\Validation\Validator */ protected function validateAbilities($validator) { $abilities = implode(',', array_keys(Spark::tokensCan())); $validator->sometimes('abilities', 'required|array|in:' . $abilities, function () { return count(Spark::tokensCan()) > 0; }); return $validator; }
public function validate(\Illuminate\Validation\Validator $validator) { if ($validator->fails()) { $this->validation_errors = $validator->messages(); return false; } return true; }
public function getMessages() { if ($this->_validator !== null) { return $this->_validator->messages()->getMessages(); } else { return $this->_messages; } }
/** * Validate that the value is greater than another attribute * * @param string $attribute * @param mixed $value * @param array $parameters * @param Illuminate\Validation\Validator $validator * @return boolean */ public function validateGreaterThanOther($attribute, $value, $parameters, Validator $validator) { // Require at least one parameter $this->requireParameterCount(1, $parameters, 'greater_than_other'); $otherField = $parameters[0]; $otherValue = $this->getValue($otherField, $validator->getData(), $validator->getFiles()); return isset($otherValue) && is_numeric($value) && is_numeric($otherValue) && $value >= $otherValue; }
protected function formatErrors(Validator $validator) { $errors = $this->parseErrorRest($validator->errors()->getMessages()); $response = new ResponseWService(); $response->setDataResponse(ResponseWService::HEADER_HTTP_RESPONSE_SOLICITUD_INCORRECTA, array(), $errors, 'Datos Invalidos del formulario'); $response->response(); // return $validator->errors()->all(); }
function it_returns_messages_on_failed_validation(Validator $validator, MessageBag $bag) { $validator->setData($data = [])->shouldBeCalled(); $validator->passes()->willReturn(false); $validator->messages()->willReturn($bag); $bag->all()->willReturn($messages = ['foo' => 'failed']); $this->validate($data)->shouldReturn(false); $this->getMessages()->shouldReturn($messages); }
/** * Return the validation errors with :field-:message format * * @return mixed */ public function getValidationErrors() { $errors = []; $messages = $this->validation->messages(); foreach ($messages->getMessages() as $key => $message) { $errors[$key] = $message[0]; } return $errors; }
/** * @param string $attribute * @param mixed $value * @param array $parameters * @param \Illuminate\Validation\Validator $validator * * @return bool */ public function validateCurrencySupported($attribute, $value, $parameters, $validator) { $manager = $this->manager; /** @var \Illuminate\Validation\Validator $validator */ $validator->addReplacer('currency_supported', function ($message, $attribute, $rule, $parameters) use($manager) { return trans("currencies::validation.currency.supported", ['attribute' => $attribute]); }); return in_array($value, $manager->getSupported()); }
/** * Test Valid Data * @return bool */ public function isValid() { $vRules = $this->getValidationRules(); $rules = $vRules->getRules(); $messages = $vRules->getMessages(); $currentData = $this->export(); $this->validator = Validator::make($currentData, $rules, $messages); return $this->validator->passes(); }
/** * Call the custom plan eligibility checker callback. * * @param \Illuminate\Validation\Validator $validator * @param \Laravel\Spark\Plan $plan * @return void */ protected function callCustomCallback($validator, $plan) { try { if (!Spark::eligibleForTeamPlan($this->route('team'), $plan)) { $validator->errors()->add('plan', 'This team is not eligible for this plan.'); } } catch (IneligibleForPlan $e) { $validator->errors()->add('plan', $e->getMessage()); } }
/** * Validates current attributes against rules */ public function validate() { static::fireModelEvent('validating'); $v = $this->validator->make($this->attributes, $this->fixRules(static::$rules), static::$messages); if ($v->passes()) { return true; } $this->setErrors($v->messages()); return false; }
/** * Setup the "after" callabck for the validator. * * @param \Illuminate\Validation\Validator $validator * @return \Illuminate\Validation\Validator */ protected function after($validator) { return $validator->after(function ($validator) { if ($this->coupon) { $this->validateCoupon($validator); } if ($this->invitation) { $this->validateInvitation($validator); } }); }
/** * Validate that the maximum number of teams hasn't been exceeded. * * @param \Illuminate\Validation\Validator $validator * @param \Illuminate\Contracts\Auth\Authenticatable $user * @return void */ protected function validateMaximumTeamsNotExceeded($validator, $user) { if (!($plan = $user->sparkPlan())) { return; } if (is_null($plan->teams)) { return; } if ($plan->teams <= $user->ownedTeams()->count()) { $validator->errors()->add('name', 'Please upgrade your subscription to create more teams.'); } }
/** * Validate that the date is after another attribute date * * @param string $attribute * @param mixed $value * @param array $parameters * @param Illuminate\Validation\Validator $validator * @return boolean */ public function validateAfterOther($attribute, $value, $parameters, Validator $validator) { // Require at least one parameter $this->requireParameterCount(1, $parameters, 'after_other'); // Get the other value $otherField = $parameters[0]; $otherValue = $this->getValue($otherField, $validator->getData(), $validator->getFiles()); // Convert the values to dates if not already $value = $this->asDateFromValue($value); $otherValue = $this->asDateFromValue($otherValue); // Compare that the date is after the other date return isset($value) && isset($otherValue) && $value >= $otherValue; }
/** * Sets data for validate remote rules. * * @param $attribute * * @return \Illuminate\Validation\Validator */ protected function setRemoteValidation($attribute, BaseValidator $validator) { if (!array_key_exists($attribute, $validator->getRules())) { throw new BadRequestHttpException("Undefined '{$attribute}' attribute"); } $rules = $validator->getRules()[$attribute]; $rules = $this->purgeNonRemoteRules($rules, $validator); $validator->setRules([$attribute => $rules]); if (empty($validator->getRules()[$attribute])) { throw new BadRequestHttpException("No validations available for '{$attribute}'"); } return $validator; }
/** * Validates the model. * * @param array $customRules * @param array $customMessages * @param array $attributeNames * * @return bool */ protected function runValidation(array $customRules = [], array $customMessages = [], array $attributeNames = []) { $rules = empty($customRules) ? $this->getRules() : $customRules; $messages = empty($customMessages) ? $this->getCustomMessages() : $customMessages; $attributeNames = empty($attributeNames) ? $this->getAttributeNames() : $attributeNames; $attributes = $this->prepareAttributes(); $this->validator = $this->makeValidator($attributes, $rules, $messages); $this->validator->setAttributeNames($attributeNames); $success = $this->validator->passes(); if (!$success) { $this->setErrors($this->validator->errors()); } return $success; }
/** * fetch error messages from validator and optionally prepend them with a custom message * @param Validator $validator */ protected function fetchMessages(Validator $validator) { /** * $errors array is constructed like: field1 => array(0 => 'error message 1', 1 => 'error message 2' ...) * I will prepend the custom error message (added by addValidation()) to this messages array per field */ $this->errors = $validator->getMessageBag()->getMessages(); foreach ($this->errors as $name => &$messages) { if (!empty($this->validations[$name]['message'])) { $attributeName = str_replace('_', ' ', $name); $customMessage = str_replace(':attribute', $attributeName, $this->validations[$name]['message']); array_unshift($messages, $customMessage); } } }
public function validate() { $data = $this->toArray(); $this->validator = Validator::make($data, $this->getSingleValidator()); $result = !$this->validator->fails(); $this->failed = $this->validator->failed(); foreach ($this->getAllValidators() as $key => $validate) { $validator = Validator::make($data[$key], $validate->getSingleValidator()); $result = !$validator->fails() && $result; if ($validator->fails()) { $this->failed = array_merge($this->failed, [$key => $validator->failed()]); } } return $result; }
/** * Determine if the data passes the validation rules. * * @return bool */ public function passes() { if ($this->isRemoteValidationRequest()) { return $this->validateJsRemoteRequest($this->data['_jsvalidation'], [$this, 'parent::passes']); } return parent::passes(); }
public function routeIsUnique($attribute, $value, $parameters, Validator $validator) { $validator->setFallbackMessages(array_merge($validator->getFallbackMessages(), ['unique_route' => 'this route already exists'])); $validates = false; $value = Handle::normalizeUrl($value); try { $routes = Route::getRoutes(); $request = Request::create($value); $routes->match($request); // route exists } catch (\Exception $e) { // route doesn't exist $validates = true; } return $validates; }