Laravel-4 Validation - php

What is the best way to validate amount in laravel?
This is my code.
public static $rules = array(
'date' => 'required',
'payer' => 'required',
'category' => 'required',
'method' => 'required',
'creditAmount' => 'required|integer'
);
I don't want to limit the user. But amount could be like simple ditigs 33 or in the floating values like 33.45

May be you can can use as numeric:
public static $rules = array(
'creditAmount' =>'required|numeric'
));
I guess it works!

You probably want something like this:
public static $rules = array(
'date' => 'required',
'payer' => 'required',
'category' => 'required',
'method' => 'required',
'creditAmount' => array('required', 'regex:/^\d*(\.\d{2})?$/')
));
I'm no regex pro so you may need to tweak that part, but the point is you probably want to use the regex validator for something like this.

Related

YouTube embed URL validation regex in Laravel 8 in controller

I want to validate my youtube URL like this https://www.youtube.com/embed/xxxxxxxx. How to use the regex in variable link for this?
my code is like this in controller
$validatedData = $request->validate([
'title' => 'required',
'subtitle' => 'required|unique:news',
'category' => 'required',
'link' => 'required|regex:??',
'image1' => 'required|image',
'image2' => 'image',
'image3' => 'image',
'image4' => 'image',
'content' => 'required'
]);
You need to add some custom validation logic for achieving this .Hope this code snippet can help you-
'link' => [
'required',
'url',
function ($attribute, $requesturl, $failed) {
if (!preg_match('/(youtube.com|youtu.be)\/(embed)?(\?v=)?(\S+)?/', $requesturl)) {
$failed(trans("general.not_youtube_url", ["name" => trans("general.url")]));
}
},
]
Or like below-
public function passes($attribute, $requesturl)
{
return (bool) preg_match('/^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/',$requesturl);
}
'link' => new RuleYoutube,
You can use like this, we need to use array for regex validation in laravel.
// ^(?:https?:\/\/)? : Optional protocol
// (?:m\.|www\.)? : Optional subdomain
// (?:youtu\.be\/|youtube\.com\/ : Mandatory domain name with .be or .com TLD
// (?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$ : Mandatory query string
// /i : Case insensitive match
$request->validate($request, [
'link' => ['required', 'regex:/^(?:https?:\/\/)?(?:m\.|www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/i']
]);

laravel validation error when trying to update

When I try to update a post if I dont change value of slug , laravel return this error:
The slug has already been taken.
Here is my validation:
$this->validate($request, [
'name' => 'required',
'content' => 'required',
'excerpt' => 'required',
'type' => 'required',
'slug' => 'required | unique:providers'
]);
when you're updating records and there is unique validation is added. You should pass the id of which record you're inserting.
While Update
'slug' => 'required | unique:providers,slug,'.$providerId
While insert
'slug' => 'required | unique:providers'
You need to add an except rule to your unique case to exclude the current ID from check:
$this->validate($request, [
'name' => 'required',
'content' => 'required',
'excerpt' => 'required',
'type' => 'required',
'slug' => 'required|unique:providers,id,' . $provider->id
]);
Make the column and the id that you pass to use your table's data. I am just giving you an idea on what you need to add.
You need to tell the validator to do an exception for the current entity you're updating.
$this->validate($request, [
'name' => 'required',
'content' => 'required',
'excerpt' => 'required',
'type' => 'required',
'slug' => 'required|unique:providers,slug,'.$providerId
]);
When adding:
use Illuminate\Support\Str;
.
.
$slug = Str::slug($request->name, '-');
$exists = Provider::where('slug', $slug)->first();
if($exists) {
$slug = $slug.'-'.rand(1000,9999);
}
When updating:
$request->validate([
'slug' => 'required|unique:providers,slug,'.$provider_id.',id',
]);

How validate param only if user is guest in laravel?

I want validate name and email (do required) only if user is guest. How I can do it correctly?
I tried paste the if condition. But I don't think this is correct:
if (Auth::check()) {
$request->validate([
'name' => 'required|string',
'email' => 'required|string',
'body' => 'required|string',
'type' => 'required|integer|in:1,2,3'
]);
} else {
$request->validate([
'body' => 'required|string',
'type' => 'required|integer|in:1,2,3'
]);
}
I can't think of a validation rule that'll do this, but you can at least get the code a little cleaner by skipping the else condition, for instance like so:
$rules = [
'body' => 'required|string',
'type' => 'required|integer|in:1,2,3',
];
if (Auth::guest()) {
$rules['name'] = 'required|string';
$rules['email'] = 'required|string';
}
$request->validate($rules);
Another option would be to simply check the requirement within the array and just skip the field in the validation for authorised users. It's shorter, but not quite as clean:
$request->validate([
'body' => 'required|string',
'type' => 'required|integer|in:1,2,3',
'name' => Auth::guest() ? 'required|string' : '',
'email' => Auth::guest() ? 'required|string' : '',
]);
By the way, I would recommend validating the email address as an email address: https://laravel.com/docs/5.7/validation#rule-email

How to validate without request in Laravel

I need to validate an array but without a request.
In laravel docs validation is described like this:
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
But I can't use $request because the data comes from an external api and the validation is not inside a controller. How can I validate this array? For example:
$validatedData = validate([
'id' => 1,
'body' => 'text'
], [
'id' => 'required',
'body' => 'required'
]);
Should be. Because $request->all() hold all input data as an array .
$input = [
'title' => 'testTitle',
'body' => 'text'
];
$input is your custom array.
$validator = Validator::make($input, [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
Validator::make expects array and not a request object.
You can pass any array and implements the rules on it.
Validator::make(['name' => 'Tom'], ['name' => 'required', 'id' => 'required']);
And it will validate the array. So $request object is not necessary.
You can achieve this by create request object like so:
$request = new Request([
'id' => 1,
'body' => 'text'
]);
$this->validate($request, [
'id' => 'required',
'body' => 'required'
]);
and thus you will get all the functionality of the Request class
$request->all() is array not request object.
This code will work:
$data = [
'id' => 1,
'body' => 'text'
];
$validator = Validator::make($data, [
'id' => 'required',
'body' => 'required',
]);
You can also merge data with the request object:
$data = ['id' => 1];
$request->merge($data);
Then validate as per usual.

Query String validation Laravel

I don't know how to get the query string array to validate in Laravel Validation.
here is my code
public function addUserByAdmin(Request $request){
$this->validate($request,[
'name' => 'required',
'fullname' => 'required',
'password' => 'required',
'position' => 'required',
'phone' => 'required'
]);
$uesrAction = new UserAction($this->repository);
$user = $uesrAction->addUser($request->input('phone'),$request->input('password'),$request->input('name'),$request->input('fullname'),$request->input('position'));
if($user){
return response()->json(['success' => 'success','user'=>$user]);
}
return response()->json(['success' => 'fail']);
}
but validation doesn't work.Then I tried Validation::make() method and also didn't work.
My URL be like
http://localhost:8000/admin/users/add-user?phone=abcdefg&password=erer&name=ere&fullname=rere&position=343
If you are using laravel 5.5, change your code as follows:
public function addUserByAdmin(Request $request){
$validatedData = $request->validate([
'name' => 'required',
'fullname' => 'required',
'password' => 'required',
'position' => 'required',
'phone' => 'required'
]);
// ...
}
One of the features that was added in this update is that other way to use the validate() method:
More info:
https://laravel.com/docs/5.5/validation#quick-writing-the-validation-logic
https://laravel.com/docs/5.5/releases

Categories