Adding a custom video length validaiton rule but the :max_duration is never replaced in the error message addReplacer method is never called. Is there a livewire way of doing this?
Validator::extend('video_length', function ($attribute, $value, $parameters, $validator) {
$max_seconds = $parameters[0];
// Replace dynamic variable
$validator->addReplacer('video_length_duration', function ($message, $attribute, $rule, $parameters) use ($max_seconds) {
return trim(str_replace(':max_duration', gmdate("H:i:s", $max_seconds), $message));
});
return false;
}, 'Video duration must be less then :max_duration');
$this->validate([
'file' => 'required|file|max:102400|video_length:86400',
]);
Related
I need to check some special validation in my action store
public function store(Request $request) {
$this->validate($request, [
'practice'=>'required|max:100',
'project'=>'required',
'work_place'=>'required',
'telephone_1'=>'required',
'date_recurring_for_beginning' => 'required|date',
'date_recurring_for_end' => 'required|date|after_or_equal:date_recurring_for_beginning',
]);
RequestCollaborator::create($request->all());
return redirect()->route('requestsCollaborator.index')
->with('flash_message',
trans('request.request_created'));
}
I have to validate if the difference between date_recurring_for_beginning and date_recurring_for_end is 3 months?
there is any solution for doing this or I have to create a custom validation?
You can use Validator::extend() and can create your custom validation rule. Like
Validator::extend('valid_date_range', function ($attribute, $value, $parameters, $validator) {
$dateBeginning = \Carbon::createFromFormat('Y-m-d', $parameters[0]); // do confirm the date format.
$dateEnd = \Carbon::createFromFormat('Y-m-d', $value);
return $dateBeginning->diffInMonths($dateEnd) == $parameters[1];
});
You can use this like:
'date_recurring_for_end' => 'required|date|valid_date_range:date_recurring_for_beginning,3'
For more details about the custom validation. Please follow the documentation.
https://laravel.com/docs/5.8/validation
Create a custom validation rule within your app/Providers/AppServiceProvider:
public function boot()
{
Validator::extend('date_difference', function ($attribute, $value, $parameters, $validator) {
$firstDate = Carbon::parse($parameters[0]);
$secondDate = Carbon::parse($parameters[1]);
$minDifference = (int)$parameters[2];
if($firstDate->diffInMonths($secondDate) < $minDifference)
return false;
return true;
});
}
To use this rule:
$this->validate([
'some_field' => 'date_difference:date_one,date_two,3',
]);
Hope it helps.
I have a WYSIWYG editor. When users keep pressing space in the editor, the input will be like this.
"<p> </p>"
To prevent this I modified the all method in Request class like this to remove whitespace and tags.
public function all()
{
$input = parent::all();
$input['body'] = strip_tags(preg_replace('/\s+/', '', str_replace(' ',"", $input['body'])));
//modify input here
return $input;
}
This works great.
However, the problem here is if other validation rules fail, the return value from old helper function is modified by the method.
So, if the original input is like this
"""
<p> <iframe src="//www.youtube.com/embed/Mb5xcH9PcI0" width="560" height="314" allowfullscreen="allowfullscreen"></iframe></p>\r\n
<p>This is the body.</p>
"""
And if other validation rules fail I get this as an old input.
"Thisisthebody."
So, is there any way to get original request inputs as an old input when validations failed?
Here is my form request.
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
use Illuminate\Validation\Factory as ValidationFactory;
class ArticleRequest extends Request
{
public function all()
{
$input = parent::all();
$input['body'] = strip_tags(preg_replace('/\s+/', '', str_replace(' ',"", $input['body'])));
//modify input here
return $input;
}
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'title' => 'required|min:3|max:40',
'tags.*' => 'required',
'body' => 'required|min:50',
//up to 6mb
'thumbnail'=>'image|file|max:10240'
];
}
public function messages()
{
return [
'title.required' => 'タイトルを入力してください',
'title.min' => 'タイトルは3文字以上でお願いします',
'title.max' => 'タイトルは40文字以下でお願いします',
'body.min' => '本文は50文字以上お書きください',
'body.required' => '本文を入力してください',
'tags.*.required' => 'タグを選んでください',
'thumbnail.image' => '画像の形式はjpeg, bmp, png, svgのいずれかをアップロードできます',
'thumbnail.file' => 'フォームから画像をもう一度アップロードしてください',
'thumbnail.max' => 'ファイルは10MBまでアップロードできます',
];
}
}
Create a custom validator which strips the tags, counts characters but does not modify the content itself.
Validator::extend('strip_min', function ($attribute, $value, $parameters, $validator) {
$validator->addReplacer('strip_min', function($message, $attribute, $rule, $parameters){
return str_replace([':min'], $parameters, $message);
});
return strlen(
strip_tags(
preg_replace(
'/\s+/',
'',
str_replace(' ',"", $value)
)
)
) >= $parameters[0];
});
and in your validation.php lang file add:
'strip_min' => 'The :attribute must be at least :strip_min characters.'
source: https://stackoverflow.com/a/33414725/2119863
I have a form which performs the inserting function, the related method is :
public function addthread(Request $request) {
//validate
$this->validate($request, [
'title' => 'required|unique:thread|max:255',
'num_opt' => $this->checkOpt($request),
]);
}
I want to use a custom function to validate the num_opt elements,:
protected function checkOpt($request, Validator $validator) {
//$num_opt = $request->input('num_opt');
if ($request->has('$num_opt')) {
//$validator->errors()->add ??
How to customize the error message?
}
//die();
}
Questions:
Is the above code practice is wrong or not?
How can I access $validator and customize the error message in the checkOpt function?
I have been following the docs and a couple stackoverflow post but it seems I made a mistake I can't figure out. I get the the error Method[validateOnOrAfter] does not exist.
app/start/global.php
ClassLoader::addDirectories(array(
app_path().'/commands',
app_path().'/controllers',
app_path().'/models',
app_path().'/database/seeds',
app_path().'/custom',
));
app/custom/validation.php
<?php
class CustomValidator extends Illuminate\Validation\Validator
{
public function validateOnOrAfter($attribute, $value, $parameters)
{
$OnOrAfter = strtotime($this->getValue($parameters[0]));
$ToValidateDate = strtotime($value);
return ($OnOrAfter >= $ToValidateDate);
}
}
Validator::resolver(function($translator, $data, $rules, $messages)
{
$messages = array(
'on_or_after' => 'The :attribute must be on of after :value'
);
return new CustomValidator(($translator, $data, $rules, $messages);
}
Edit
In desperation I also tried using the other method in the docs Validator::extend directly in the controller#store method (had to make some changes to code) and that does find the method but it does nothing in my validation despite the return value being false.
app/controller/ProgramSession#store
Validator::extend( 'on_or_after', function($attribute, $value, $parameters)
{
$OnOrAfterThisDate = Input::get($parameters[0]);
$ToValidateDate = ($value);
//dd(strtotime($OnOrAfterThisDate) <= strtotime($ToValidateDate));
return (strtotime($OnOrAfterThisDate) <= strtotime($ToValidateDate));
});
Validator::replacer('on_or_after', function($message, $attribute, $rules, $parameters)
{
$messages = array(
'on_or_after' => 'The :attribute must be on of after :parameter'
);
});
I need to check if a user has posted the same password as the one in the database. Field for old password is 'oldpass'. The custom validator i created is called 'passcheck'. It should fail or pass accordingly.
My UsersController code below doesnt work. What could have I have done wrong?
$rules = array(
'oldpass' => 'passcheck',
);
$messages = array(
'passcheck' => 'Your old password was incorrect',
);
Validator::extend('passcheck', function($attribute, $value, $parameters)
{
if(!DB::table('users')->where('password', Hash::make(Input::get('oldpass')))->first()){
return false;
}
else{
return true;
};
});
$validator = Validator::make($inputs, $rules, $messages);
You should use something like this,
$user = DB::table('users')->where('username', 'someusername')->first();
if (Hash::check(Input::get('oldpass'), $user->password)) {
// The passwords match...
return true;
}
else {
return false;
}
So, you have to get the record using username or any other field and then check the password.
#lucasmichot offered even shorter solution:
Validator::extend('passcheck', function ($attribute, $value, $parameters)
{
return Hash::check($value, Auth::user()->getAuthPassword());
});
I would make it like this:
/**
* Rule is to be defined like this:
*
* 'passcheck:users,password,id,1' - Means password is taken from users table, user is searched by field id equal to 1
*/
Validator::extend('passcheck', function ($attribute, $value, $parameters) {
$user = DB::table($parameters[0])->where($parameters[2], $parameters[3])->first([$parameters[1]]);
if (Hash::check($value, $user->{$parameters[1]})) {
return true;
} else {
return false;
}
});
This validator rule will make database query to check current user's password
You can make it even shorter and save query:
Validator::extend('passcheck', function ($attribute, $value, $parameters) {
return Hash::check($value, Auth::user()->getAuthPassword());
});
Please dont tie your rule to an Html element. Use the parameters Laravel provides to create your custom rules. This would be (asuming that you have a user authenticated):
Validator::extend('passcheck', function($attribute, $value, $parameters) {
return Hash::check($value, Auth::user()->password); // Works for any form!
});
$messages = array(
'passcheck' => 'Your old password was incorrect',
);
$validator = Validator::make(Input::all(), [
'oldpass' => 'passcheck',
// more rules ...
], $messages);