I've just started to test out Laravel. I'm using a form with some fields and trying to validate the inputs using Laravel's built-in validator class.
$input = Input::all();
$rules = array(
'fname' => 'required|max:100',
'lname' => 'required|max:100',
'email' => 'required|email',
);
$validation = Validator::make($input, $rules);
if ($validation->fails()){
return Redirect::to('inputform')
->with('input_errors', $validation->errors);
}
Everything goes well, and the validation check works. When validation fails, I put the errors in a session variable called input_errors and pass it to the view. My problem is that I can't seem to display the errors. I tried a foreach loop using the blade templating engine as given below:
#foreach (Session::get('input_errors') as $message)
{{ What Should I put here? }}
#endforeach
How can I display the errors that are being returned as an array. I tried referencing it as $message[0][0] but it didn't work.
Thanks.
EDIT: Sorry, forgot to mention that I'm using Laravel 3
The correct syntax for getting the errors is...
$messages= $validation->messages();
That alone, unfortunately, is not going to return you the messages. It's going to return a MessageBag instance. This allows you to pull out any specific messages you want or all.
If you want to get all the messages, now you can do do...
$errors = $messages->all();
That will return an array you could loop through in your view to display errors. There are also methods for getting errors on a specific field such as...
$firstNameError = $messages->first('fname');
or
$firstNameErrors = $messages->get('fname');
I also suggest when sending error messages to the view, to use...
->with_errors($validation);
That will flash the errors to session and automatically assume you are sending them as an $errors variable. Then you may display the errors in your view with.
{{ $errors->first('fname') }} // Blade approach
<?php echo $errors->first('email'); ?> // Non-blade approach
This way, you don't have to add logic to your views trying to determine if the variable exists before you should try and echo it.
http://four.laravel.com/docs/validation
Related
I'm trying to leverage any automatic handling of validation and displaying errors for a form using multiple entities.
The user can dynamically create multiple new entities via the form UI. The data is marshalled through newEntities():
$this->MyModel->newEntities($data);
The first part of the problem I have is that in order to check if validation failed on any of the entities, I have to do it manually by checking every entity:
$errors = false;
foreach ($entities as $entity) {
if ($entity->errors()) {
$errors = true;
break;
}
}
if (!$errors) {
// Save...
Does Cake provide anything out of the box which allows you to check if newEntities() failed validation on any of its entities? If not, then never mind...
The main problem is how I get the errors from the individual entities to then show inline in my form next to the relevant inputs.
<?= $this->Form->create(); ?>
What can I pass to create() to link it to the entities? At the moment there doesn't seem to be any way for it to know what happens once the form is submitted, and therefore doesn't show errors.
My form inputs are created using the standard array notation, where $i comes from the loop building the form inputs from all the entities.
$this->Form->hidden("MyModel.$i.field");
simply pass the array of entities to your form
$this->Form->create($entities);
also you don't have to specify the model name in the input name. Simply
$this->Form->hidden("$i.field");
and not
$this->Form->hidden("MyModel.$i.field");
Use newEntity and add those to an array. Loop over that array accessing errors().
$array = [];
$array[] = $TableRegistry->newEntity([
'hi' => 'hey'
]);
foreach($array as $r){
var_dump($r->errors());
}
Hopefully that works with your use-case. I've never used newEntities, but you may be able to iterate over that as well?
I got stuck with this stupid error messages in Zend Framework 2. Spent two hours and nothing, I still got two different error messages with NotEmpty validator.
$nameNotEmptyMessage = 'Pole wymagane';
$inputFilter->add(array(
'name' => 'name',
'required' => true,
'filters' => array(
new Filter\StringTrim()
),
'validators' => array(
new Validator\NotEmpty(array(
'messages' => array(
Validator\NotEmpty::INVALID => $nameNotEmptyMessage,
Validator\NotEmpty::IS_EMPTY => $nameNotEmptyMessage
)
))
)
));
And what? It works pretty cool when I send form with "name" element inside it. When it's empty, I've got my message. But, when I send form without the "name" element inside it, the message is still "Value is required and can't be empty"! Why?
I need to have in both cases the same message because sometimes the form won't have "name" element.
Thank you guys very much!
Thanks for replying to the comment to clarify the problem. First I must say, I feel your pain on this one. After having not used ZF2 for over a year and spending some time figuring this out, it highlights yet another painful thing in ZF2.
That said, here is my simple solution. Not necessary correct, or the best way to go about it but it solves your problem with the least amount of code. In your controller where you instantiate and validate the form, add this code before you call new Form:
if (!isset($_POST['name'])) {
$this->getRequest()
->setPost(
new \Zend\Stdlib\Parameters(
array('name' => '')
)
);
}
This seemed the simplest route rather than setting up a default validation translator and adding a duplicate message. It is just checking to see if the name field was not present, and if so sets it with any empty value.
Now the reason why we have to do this:
This happens because of how \Zend\InputFilter\Input works. When the InputFilter runs, it sees the element is missing. It then checks the required property, sees it's true but the input has no value. No value being different than empty.
When the filter is required but has no input, \Zend\InputFilter\Input::prepareRequiredValidationFailureMessage is called. If you look at the source of that function, you'll see:
protected function prepareRequiredValidationFailureMessage()
{
$notEmpty = new NotEmpty();
$templates = $notEmpty->getOption('messageTemplates');
return [
NotEmpty::IS_EMPTY => $templates[NotEmpty::IS_EMPTY],
];
}
Notice how it creates a new NotEmpty validator and fetches its default message, thus bypassing the translation you set within the InputFilter.
The alternative:
One alternative, which may be more correct, but also requires more code and could arguably be more confusing looking back later would be to create a new class implementing \Zend\Validator\Translator\TranslatorInterface and set an array with the translation for that message and then calling \Zend\Validator\AbstractValidator::setDefaultTranslator passing that so the default translator will be used on that message.
This is just difficult because there is no short way of setting up that object because of how the classes are inherited and I wasn't able to find a quick solution to set up the default translator with just that message. Also, if you have another translator in place, it might interfere with it.
So it seems the simplest thing is to just check for the absence of that form field and populate it with any empty value if it's missing.
Hope that helps!
Other more simple way to fix this is to overwrite the Form setData($data) and to check if $data['name'] is set. Something like this:
public function setData($data)
{
if(!isset($data['name'])){
$data['name'] = '';
}
return parent::setData($data);
}
Is there a way to force an error when using Validator Class in Laravel 5.1?
For now, I've done the traditional way calling $validator = Validator::make($request->all(), $rules), which is working fine. Also, I'm attempting to make another validation (manual one) and push it into $validator, but I can't get true when I call $validator->fails().
Even using $validator->errors()->add('field','message') I couldn't force it. Is there another way?
In order to make validation fail, you need to define a validation rule that won't be met. Easiest way is to require some non-existent field.
This will do the trick:
$rules['some_non_existent_field'] = 'required';
$validator = Validator::make($request->all(), $rules);
dd($validator->fails());
I had the same problem too
adding error to Validator doesn't make It to fail, so you need to make a trap for It that forces It to, maybe a required input that doesn't even exist...
but that will make a confusing error for user (example: unreal_input is required), you'd easily change the message to explain what actually made you to fail the process...
$req = Request::all();
$rules = [/*...*/];
if(/*something's wrong*/){
$rules['unreal_input'] = 'required'; // a confusing error in your errors list...
$messages['unreal_input.required'] = '/* explain the real problem in here*/';
}
$validator = Validator::make($req, $rules,$messages);
if ($validator->fails()) return redirect()->back()->withErrors($validator)->withInput();
so in the code above you've manually checked if something's wrong, then you've made a trap for Validator, then you've changed the message to what the real problem was.
NOTE: I suggest you to use a random value instead of something like unreal_input , because If you do this, the user may(?) guess the input's name, and easily using F12 he/she would pass the validation and give some invalid data to you
I have a form in laravel 5 with all field being required. If the user doesn't input anything in the field, an error messages will be shown just under that field. The error message is shown like this:
{!!$errors->first('Name','<div class="has-error"><span></span>:message</div>')!!}
...to give you an example, if the user doesn't input anything in the field "Name", the message will be: "The name field is required."
What I want is to capture this message in a variable, something like:
$mess=something;
..i need this something...
If i do echo $mess the result should be The name field is required.
Can you help me please ?
Thanks.
This sounds like you want to capture the errors in the controller directly, right? Because you are using $this->validate() in your controller, thus returning you the errors and you can access is with the $errors variable. Is this correct so far?
If yes, then don't use $this->validate(), but this instead
$v = Validator::make($request->all(), [
'title' => 'required|unique|max:255',
'body' => 'required',
]);
if ($v->fails()) {
return view('viewname', ['mess' => $v->errors()]);
}
This lets you save the Validator instance in a variable, and do the check manually. $v->errors() now contains all your errors, which you can return to your view as mess.
I'm using a form which contains wrapped elements. The wrapping happens in the view like described here.
My action looks like this:
$myForm = [definition here]
$myForm->setName('entity');
$myForm->setWrapElements(true);
$request = $this->getRequest();
if ($request->isPost()) {
$myEntity = new Entity();
$myForm->bind($myEntity);
$myForm->setData($request->getPost()->get('entity'));
The problem: When calling $myForm->isValid() it's invalid. When calling $myForm->getData() afterwards it's empty.
I repeated the setName and setWrapElements in the action but with or without it, it doesn't work.
Any ideas what I might be doing wrong? The form definition is untouched and works for non-wrapped forms. So I guess the error is not in there.
P.S.: An echo of $myForm->isValid() returns an empty string. Is there maybe a way to get the error message? The form fields are filled with the data I've put in there and don't show any errors.
Using the following:
$form->getMessages()
Will give you the validation messages.
You can dump the contents or loop the messages in a foreach loop. For example:
foreach($form->getMessages() as $msgId => $msg) {
echo "Validation error: $msgId => $msg"
}
can you try to add line to your code, as I can see in zend's Form.php, element names aren't wrapped with 'entity' till the moment you call prepare();
$myForm->setName('entity');
$myForm->setWrapElements(true);
$myForm->prepare(); // << add this
But I don't believe that it will help, becuase behaviour you describe looks little different. Cau you show us more source code of Entity and var_dumps of things that Aydin and Sina wanted.
In ZF2 data is not binded if the form is not valid. The reason because you see an empty string in the return of isValid is that the return type is a boolean, use var_dump instead.