I followed this short tutorial: http://blog.elenakolevska.com/laravel-alpha-validator-that-allows-spaces/.
Now my question is, how can i add errors to it? Because now i just get this as an error:
validation.alpha_spaces
I'm also curious on how to add numbers to the validator?
Thanks!
Edit:
If you don't want to open the link, this is basicly my code:
Validator::extend('alpha_spaces', function($attribute, $value) {
return preg_match('/^[\pL\s]+$/u', $value);
});
You need to pass a custom error message as well, for example:
Validator::extend('alpha_spaces', function($attribute, $value) {
// ...
});
Now prepare a message for this custom rule:
$messages = array('alpha_spaces' => 'Your custom error message for :attribute');
Use it like this (with $messages):
$validator = Validator::make($input, $rules, $messages);
Here :attribute will be replace with the form's field name.
Related
i want to validate my file, only .ico files.
Laravel dont include x-icon mime I think, how can i validate it?
$logo = $request->file('logo');
$favicon = $request->file('favicon');
$request->validate([
'logo'=>'image|mimes:png',
'favicon'=>'',
]);
Make a custom validation rule as explained here.
In short:
First do:
php artisan make:rule CheckIfFavicon
Then:
Create the validation code in the created Rules-file.
Try something like:
public function passes($attribute, $value)
{
return $value->getClientOriginalExtension() == 'ico';
}
Then ad it to the validation. Note, that if you make a custom validation class you will have to change the syntax in the $request->validate([...]) from pipe-ing to array.
$request->validate([
'favicon' => [new CheckIfFavicon],
]);
use $file->getClientOriginalExtension() in code if you only want to check file extension
$ext = $file->getClientOriginalExtension();
if($ext == 'ico'){
//uploadfile
}else{
//do something else
}
use this as reference.
To add a new validation to Laravel I have done this:
made a new file called customValidation.php in app/start/
and then included it in app/start/global.php and tested it with an echo() and it worked. So it is loaded into the application now.
Then I wrote the following code to validate checkboxes in Laravel:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
class customValidate extends Illuminate\Validation\Validator
{
public function validateCheckbox($attribute, $value, $parameters)
{
//if(isset($value)) { return true; } else { return true; }
echo "this is the: " . $value;
}
}
/**
* Resolvers for Custom Validations
*/
Validator::resolver(function($translator, $data, $rules, $message){
return new customValidate($translator, $data, $rules, $message);
});
However, in my validation rules, I define :
`array('sex'=>'checkbox')`
But it does not work. Nothing happens. No error is thrown. The application behaves as if it has not executed the function at all. Also when I echo something from within the function,nothing get echoed, another evidence for the function not being called at all.
I would create custom app/validators folder for this then.
1, Create app/validators/CustomValidate.php
<?php
class CustomValidate extends Illuminate\Validation\Validator
{
public function validateCheckbox($attribute, $value, $parameters)
{
echo "this is the: " . $value;
}
}
2, run php artisan optimize or composer dumpautoload
3, Somewhere register your custom validator. Perhaps add app/validators.php into start/global.php
Validator::resolver(function($translator, $data, $rules, $message){
return new CustomValidate($translator, $data, $rules, $message);
});
4, Validate
$rules = ['agreed' => 'checkbox'];
$data = ['agreed' => 0];
$v = Validator::make($data, $rules);
dd($v->passes());
When submitting the form, the radios were not set in their initial states, and this made Laravel not to look for the validator of the item. So, it doesn't have any workaround for that. What I did was I simply added an initial state to the radios and they worked.
Much Like said by Andreyco
I have tried showing an error message in a Controller and it doesn't work, but when I use dd, it works.
My Code:
if ($validation->fails())
{
/*Doesn't work
foreach ($validation->fails() as $messages) {
$messages // Doesn't work
}
*/
dd($validation->errors); //This works
}
I noticed none of the provided examples here actually work! So here you go. This was my found solution after realizing that validator->messages() returns a protected object which isn't retrievable.
if ($validator->fails())
{
foreach ($validator->messages()->getMessages() as $field_name => $messages)
{
var_dump($messages); // messages are retrieved (publicly)
}
}
I would reference MessageBag, which is what messages() returns. And for additional acknowledgement of the Validator class - reference this.
$validation->fails() returns a boolean of whether or not the input passed validation. You can access the validation messages from $validation->messages() or pass them to the view where they will be bound to the $errors variable.
See the validator docs.
This is what I have just used in an artisan 5.0 console command, to validate the arguments. This is in the fire() method:
// Create the validator.
$validator = Validator::make(
$this->argument(),
['field1' => 'required|other|rules']
);
// Validate the arguments.
if ($validator->fails())
{
// Failed validation.
// Each failed field will have one or more messages.
foreach($validator->messages()->getMessages() as $field_name => $messages) {
// Go through each message for this field.
foreach($messages AS $message) {
$this->error($field_name . ': ' . $message);
}
}
// Indicate the command has failed.
return 1;
}
This is an extension on the answer from #tfont
You may need to change where the message is sent ($this->error()) if this command is not being run as an console command, ie CLI, command-line.
I would like create custom validator for Symfony 1.4, for example check length name. I know that it exist, but i would like own.
I create /myapp/lib/validator/sfValidatorName.class.php
Must be there:
class sfValidatorName extends sfValidatorBase
{
protected function configure($options = array(),
$messages = array()) {
$this->addMessage('invalid', 'Invalid name!');
}
protected function doClean($value) {
}
}
and how can i add for this my function, for example:
if (count($letters) < 3) {
return 'too small';
} else if (count($letters) > 43) {
return 'too long';
}
Open /lib/validator/sfValidatorString.class.php
Model your validator after that one.
Since your example is exactly what sfValidatorString does, why don't you go look at it's source? Basically you just throw a validation error with the relevant error code (eg. invalid, min_length, max_length, ...).
By default any validator has the errors 'invalid' and 'required', but you can add your own with addMessage().
For this specific example, a much smarter choice is to configure or extend sfValidatorString.
My crazy designer would like the message "Required" displaying (in red) inside a field if the form has been submitted and it is invalid because of an empty field.
The form in question is a login prompt and I'm using a custom class that extends sfGuardFormSignin
I've managed to set the value and add a class with..
$this->widgetSchema['username']->setAttribute('class','red');
$this->widgetSchema['username']->setDefault('Required');
..but how do I do this only when the username field is invalid and because of the Required error?
I assume it's the same for the password field?
Many thanks in advance
EDIT:
Thanks for the advice greg0ire. I've had a play with that but the formatRow method of sfWidgetFormSchemaFormatter doesn't seem to be getting hit. Is this because my form extends sfGuardFormSignin and using the sfGuardAuth plugin?
class FrontendsfGuardFormSignin extends sfGuardFormSignin
{
public function configure()
{
parent::configure();
// This works!
$this->widgetSchema['username']->setLabel('Email');
// I copied this from the link you pasted
$decorator = new myWidgetFormSchemaFormatterCustom($this->getWidgetSchema());
$this->widgetSchema->addFormFormatter('custom', $decorator);
$this->widgetSchema->setFormFormatterName('custom');
}
}
/lib/widget/myWidgetFormSchemaFormatterCustom.class.php
class myWidgetFormSchemaFormatterCustom extends sfWidgetFormSchemaFormatter
{
public function __construct(sfWidgetFormSchema $widgetSchema)
{
parent::__construct($widgetSchema);
}
public function formatRow($label, $field, $errors = array(), $help = '', $hiddenFields = null)
{
// Nothing happens!?
var_dump($errors);
die();
parent::formatRow($label, $field, $errors, $help, $hiddenFields);
}
}
$widget->render(array('value' => $widget->getError()));
Designers have such crazy ideas...
You'll have to write a custom schema formatter to do this. You'll probably have to override the formatRow() method to achieve this.
Analyse the $errors array argument of this method, and if you spot the "Required" error in it, then do your special stuff. You won't need to use the code you posted in your question.