Laravel 5 Validation accept comma separated string with max 4 numbers - laravel

Laravel 5 Validation accept comma separated string with max 4 numbers
Example-
1. 1,2,3,4 --- Accepted
2. 1,2 --- Accepted
3. 1,2,3,4,5 --- Rejected
Note: I can Achieve this task by first convert the string to array and then validate the request, But i am looking for a Best approach to solve the same.

Validate it with this in your controller:
$this->validate(Request::instance(), ['field_name'=>['required','regex:/^\d+(((,\d+)?,\d+)?,\d+)?$/']]);

You can create your own custom Rule for this.
php artisan make:rule MaxNumbers
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class MaxNumbers implements Rule
{
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
return count(explode(',', $value)) < 5;
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return 'The :attribute must be max 4 numbers.';
}
}
And to use it:
use App\Rules\MaxNumbers;
$request->validate([
'field_name' => ['required', new MaxNumbers],
]);

You could use the following regex rule:
$this->validate($request, [
'field_name' => 'regex:/^[0-9]+(,[0-9]+){0,3}$/'
]);

Related

laravel validation check if input value exists in emails or users

please I want know if there is any method to validate an input if exists in column email or username
without deal with code just validation system in laravel like
'username'=>'required|exists:App\Models\User,email OR exists:App\Models\User,username'
I want to make a 'LOST PASSWORD' like wordpress
wordpress lost password system ask the users for email or username if exits it's okey if it's not display an error message
If you really need to check if the username exists as a users.email or as a users.username, you should make a Custom Validation Rule - since the exists rule can't cover both of these. Something like this should work:
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use App\Models\User;
class EmailOrUsername implements Rule
{
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
return User::where(function($q) use($value) {
$q->orWhere('email', $value)->orWhere('username', $value);
})->count() > 0;
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return 'Sorry, your credentials do not match our records.';
}
}
When you need to use it, you do it like this:
<?php
use App\Rules\EmailOrUsername;
$request->validate([
'username' => ['required', 'string', new EmailOrUsername],
]);

Laravel conditional validation rule for array items

I have the following working validation rule which checks to make sure each recipient,cc,bcc list of emails contain valid email addresses:
return [
'recipients.*' => 'email',
'cc.*' => 'email',
'bcc.*' => 'email',
];
I need to also be able to allow the string ###EMAIL### as well as email validation for each of these rules and struggling to create a custom validation rule in Laravel 5.8 (it can't be upgraded at this time).
Any idea how to go about this? If it were a higher version of Laravel I was thinking something like (not tested) to give you an idea of what I'm trying to do:
return [
'recipients.*' => 'exclude_if:recipients.*,###EMAIL###|email',
'cc.*' => 'exclude_if:recipients.*,###EMAIL###|email',
'bcc.*' => 'exclude_if:recipients.*,###EMAIL###|email',
];
In 5.8 you can create Custom Rule Object Let's see how we can actually make it work.
Create your rule with php artisan make:rule EmailRule
Make it to look like this
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class EmailRule implements Rule
{
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
if ($value === '###EMAIL###' or filter_var($value, FILTER_VALIDATE_EMAIL)) {
return true;
}
return false;
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return 'The :attribute must be valid email or ###EMAIL###.';
}
}
Include in your rules so it looks like
return [
'recipients.*' => [new EmailRule()],
'cc.*' => [new EmailRule()],
'bcc.*' => [new EmailRule()],
];
Write a test (optional)

Laravel Validation field must have 4 words

i want make field name be written in a quadrilateral
same
"andy hosam rami entaida"
or
"حسام احممد محمد متولى"
i tray
'name' => 'regex:/^[\wء-ي]+\s[\wء-ي]+\s[\wء-ي]+\s[\wء-ي]+/
in english all true put in arabic is false
regex is true i test it hear regexr.com/57s61
i can do with php in another way , so how can write in laravel ?
if(count(explode(' ',$name)) < 4)
{
$error[] ='enter full name with 4 words';
}
You can make a custom Rule class to do custom validation, in an encapsulated manner.
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class NumWords implements Rule
{
private $attribute;
private $expected;
public function __construct(int $expected)
{
$this->expected = $expected;
}
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
$this->attribute = $attribute;
$trimmed = trim($value);
$numWords = count(explode(' ', $trimmed));
return $numWords === $this->expected;
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return 'The '.$this->attribute.' field must have exactly '.$this->expected.' words';
}
}
Then you can use it anywhere in validation, as below:
public function rules()
{
return [
'name' => [ 'required', 'string', new NumWords(4)],
];
}

How to set only one NULLABLE out of two input fields

I have two input fields one as mobile_no and other as email, i want to set a condition that out of two fields if mobile_no is not given them email must be required and vice versa.
How to set nullable condition on laravel validation that only one field out of two must be required.
You can create a custom rule. So your need is opposite of what required_if rule does, so please try this one and let me know.
First create custom rule, I call it NullableIf
php artisan make:rule NullableIf
Then the implementation should be something like this:
class NullableIf implements Rule
{
private $otherField;
/**
* Create a new rule instance.
*
* #return void
*/
public function __construct( $otherField )
{
$this->otherField = $otherField;
}
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
if($this->otherField === null)
{
return $value !== null;
}
return true;
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return 'The validation error message.';
}
}
To use it you do:
$request->validate([
'field1' => [ new NullableIf(request('field2')) ],
'field2' => [ new NullableIf(request('field1')) ]
]);
I hope at least it gives you direction unless this exact implementation does not suits your needs.

How to validate images array type using rule object with custom message in Laravel

Actually, I tried to create rule object which is able to validate every image type in array of images and not only enough but also, I must to show custom message in override message function in rule object.
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class ImagesArray implements Rule
{
/**
* Create a new rule instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
return [$attribute => 'mimes:jpeg,jpg,png' ];
here i need to validate these file types.
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return 'The validation error message.';
here, I need to show my custom messgae.
}
}
You should use Request.
For example, create q request class: php artisan make:request MyRequest.
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class MyRequest extends FormRequest
{
/**
* 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 [
'image' => 'mimes:jpeg,jpg,png',
];
}
public function messages()
{
return [
'image.mimes' => 'This image is not supported.',
];
}
}
In your controller import class MyRequest and in the method use MyRequest
e.g:
public function store(MyRequest $request)
{ // your code
}
Let me know if that was helpful. Thanks!
When validating arrays or nested parameters, you should use . in your rules access a specific array index. but if you want to apply a rule to every index on that array, you can use .*.
$validator = Validator::make($request->all(), [
'image.*' => 'mimes:jpeg,jpg,png',
], [
'image.*' => 'Invalid file type.',
]);
Or if you're using Request Forms
public function rules(){
return [
'image.*' => 'mimes:jpeg,jpg,png',
];
}
public function mesages(){
return [
'image.*' => 'Invalid file type.',
];
}
For more info, see Laravel's Documentation on Validation Arrays

Resources