Laravel custom validation rule - php

How can i make a custom validation rule to an input which value must be an integer and starting with 120?
I already read about making custom messages but didnt understand about rules.
I want to use a regex to validate the data. ^120\d{11}$ here is my regex.
I'm new in Laravel that's why cant now imagine how to do that.
A custom validation to use it in $this->validate($request, []);
Now i'm validating data like so:
$this->validate($request, [
'user_id' => 'integer|required',
'buy_date' => 'date',
'guarantee' => 'required|unique:client_devices|number',
'sn_imei' => 'required|unique:client_devices',
'type_id' => 'integer|required',
'brand_id' => 'integer|required',
'model' => 'required'
]);
The input that i want to add custom validation is guarantee

The quickest neatest way is an inline validator in your controller action:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'number' => [
'regex' => '/^120\d{11}$/'
],
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
return view('welcome');
}
Where number is the name of the field being submitted in the request.
If you have a lot of validation to do, you might want to consider using a Form Request instead, as a way of consolidating a lot of validation logic.

You can create custom validations in your controller as:
$name = Input::get('field-name')
$infoValidation = Validator::make(
array( // Input array
'name' => $name,
),
array( // rules array
'name' => array("regex:/^120\d{11}$"),
),
array( // Custom messages array
'name.regex' => 'Your message here',
)
); // End of validation
$error = array();
if ($infoValidation->fails())
{
$errors = $infoValidation->errors()->toArray();
if(count($errors) > 0)
{
if(isset($errors['name'])){
$response['errCode'] = 1;
$response['errMsg'] = $errors['name'][0];
}
}
return response()->json(['errMsg'=>$response['errMsg'],'errCode'=>$response['errCode']]);
}
Hope this helps.

Since Laravel 5.5, you can make the validation directly on the request object.
public function store(Request $request)
{
$request->validate([
'guarantee' => 'regex:/^120\d{11}$/'
]);
}

Related

Valdiation data which send by ajax

I make form by React. After submitted form, I need to validate data from Laravel. Problem is that sending data is diffrent than normal form. So any values from dorm is in array data.
//normal form
$request->title
//sending from React
$request->data['title']
So, look at this code
class articleRequest extends Request
{
public function rulse(){
return [
'title' => 'required',
//other rules
];
}
}
class ArticleController extends Controller
{
public function atoreArticle(articleRequest $request){
Textads::create([
'title'=> $request->data['title'],
//other
]);
}
}
But I have an error that title field is required. Without valdiation everything is ok. How I can solve my problem?
You can try this -
$rules = [
'title' => 'required',
//other rules
];
Validator::make($request->all(), $rules)->validate();
will this work? or $request->all()->data ?
$validator = Validator::make($request->data, [
title'' => 'required'
],[
//custom error message if needed
]);
if ($validator->fails()) {
return response()->json([
'success' => false,
'data' => $validator->messages(),
'message' => "error"
], 422);
}

validate on array parameter igoners my rules and update

I have a function that updates the data. It receives the data as an array parameter.
I tried use validator make, and also validate helper method but it didn't work because it's only work for requests, and i tried also in validator make as the code below and also 'params.name' but it didn't work.
public function updateCompany(array $params): bool
{
if( Validator::make($params,[
'name'=> 'required|min:3|unique:company',
'email'=> 'required|min:4|unique:company|email'
])) {
return $this->update($params);
}
}
After trying this it didn't give me any error put it ignores my validation rules and update anyway.
Just use
public function updateCompany(Request $request)
then you could do something like this:
$rules = array('name' => 'required',
'email' => 'email|required|unique:users',
'name' => 'required|min:6|max:20');
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return ['status' => 422, 'errors' => $validator->errors()];
}

Laravel 5.3: Form Validation does not show errors

I am trying to create a register form using Laravel.
I created a request \App\Http\Requests\RegisterNewUserRequest. This is the rules() method:
public function rules()
{
return [
'email' => 'required|email|min:6|max:255|unique:members',
'password' => 'required|min:6|max:16|confirmed',
'name' => 'required|min:2|max:255|alpha',
'surname' => 'required|min:2|max:255|alpha',
];
}
This is my Membership Controller
//Route::post('{locale}/create-new-user, 'MemberController#create_new_user');
public function create_new_user($locale, RegisterNewUserRequest $request)
{
$input = $request->all();
$input['ip'] = Request::ip();
Member::create($input);
return redirect("/$locale/create-account");
}
I violate validation rules while entering information. For example, I enter two different passwords, and enter 1 character to the email field. It does not say anything about it. Also It does not save the data into database. The page is redirected to same empty register form again.
I have got a validation summary in my view
...
#foreach($errors->all() as $e)
<li>{{$e}}</li>
#endforeach
...
I trace data posted. It is posted. But something is weird in flow.
EDIT
This happens also in my contact form. If I fill the contact form properly, it sends an e-mail. But if I violate the validation rules, it doesn't say anything about validation and not send e-mail.
This is my Contact page controller
/**
* #param Requests\SendMessageRequest $
*/
public function sendMessage($locale, SendMessageRequest $request)
{
// validation
// $this->validate($request,
// ['name' => 'required|min:3',
// 'email' => 'required|min:5',
// 'subject' => 'required|min:3',
// 'message' => 'required|min:15'
// ]);
$formData = $request->all();
$formData['ip'] = Request::ip();
Mail::send('contact.send', compact('formData'),
function ($message) use ($formData) {
$message->from('frommail#example.com', 'Example')
->bcc(['bccmail#example.com'])
->to('tomail#example.com')
->subject($formData['subject']);
}
);
}
\App\Http\Requests\SendMessageRequest file's rules() method
public function rules()
{
return [
'name' => 'required|min:3',
'email' => 'required|min:5',
'subject' => 'required|min:3',
'message' => 'required|min:15',
];
}
Actually it was working before. After adding multi language feature validation did not worked. I do not know if there is any relation.
I suspect about use statements at the top of controllers and requests.

How to validate array input in laravel?

<input type="text" name="name[2]">
I tried validate like this, but didn't work correctly
$valid = Validator::make($request->all(), [
//'name.2' => 'required',
'name[2]' => 'required',
]);
-- Laravel Framework version 5.3.26
A nice way would be using Form Requests and creating dynamic rules for your arrays, like this
public function rules()
{
$rules = [
'name' => 'required|max:255',
];
foreach($this->request->get('items') as $key => $val)
{
$rules['items.'.$key] = 'required|max:10';
}
return $rules;
}
Here's a nice article talking about this: https://ericlbarnes.com/2015/04/04/laravel-array-validation/
You may also validate each element of an array. For example, to validate that each e-mail in a given array input field is unique, you may do the following:
$validator = Validator::make($request->all(), [
'person.*.email' => 'email|unique:users',
'person.*.first_name' => 'required_with:person.*.last_name',
]);

Laravel validation OR

I have some validation that requires a url or a route to be there but not both.
$this->validate($request, [
'name' => 'required|max:255',
'url' => 'required_without_all:route|url',
'route' => 'required_without_all:url|route',
'parent_items'=> 'sometimes|required|integer'
]);
I have tried using required_without and required_without_all however they both get past the validation and I am not sure why.
route is a rule in the route field
I think you are looking for required_if:
The field under validation must be present if the anotherfield field is equal to any value.
So, the validation rule would be:
$this->validate($request, [
'name' => 'required|max:255',
'url' => 'required_if:route,""',
'route' => 'required_if:url,""',
'parent_items'=> 'sometimes|required|integer'
]);
I think the easiest way would be creation your own validation rule. It could looks like.
Validator::extend('empty_if', function($attribute, $value, $parameters, Illuminate\Validation\Validator $validator) {
$fields = $validator->getData(); //data passed to your validator
foreach($parameters as $param) {
$excludeValue = array_get($fields, $param, false);
if($excludeValue) { //if exclude value is present validation not passed
return false;
}
}
return true;
});
And use it
$this->validate($request, [
'name' => 'required|max:255',
'url' => 'empty_if:route|url',
'route' => 'empty_if:url|route',
'parent_items'=> 'sometimes|required|integer'
]);
P.S. Don't forget to register this in your provider.
Edit
Add custom message
1) Add message
2) Add replacer
Validator::replacer('empty_if', function($message, $attribute, $rule, $parameters){
$replace = [$attribute, $parameters[0]];
//message is: The field :attribute cannot be filled if :other is also filled
return str_replace([':attribute', ':other'], $replace, $message);
});

Categories