Ignore Extra Spaces Mid String Using Laravel Min Validation Rule - php

Using the following validation rules:
'somefield' => 'required|min:20',
An input value of "Extra space." will pass min:20 validation.
What is the best way to ignore more than single spaces in the middle of a string when applying the min validation rule so the above input value would fail? Not looking for a client-side solution.

Use method prepareForValidation() in FormRequeet, try:
use Illuminate\Support\Str;
/**
* Prepare the data for validation.
*
* #return void
*/
protected function prepareForValidation()
{
$this->merge([
'somefield' => Str::squish(' laravel framework ');
// laravel framework
]);
}
References:
https://laravel.com/docs/9.x/validation#preparing-input-for-validation
https://laravel.com/docs/9.x/helpers#method-str-squish

You can use this simple validation.
'somefield' => ['required','min:20','regex:/^\S*$/u']

Related

How to validate multiple fields selectively using a common class in PHP laravel while returning all errors

Just started with my first PHP laravel project, and I have this
UserRepository.php
public function validateNewEmail(Request $request, $emailName) {
$request->validate([
$emailName => ['required', 'email', 'unique:users'],
]);
}
public function validateNewPassword(Request $request, $passwordName) {
$request->validate(
// rule
[
$passwordName => ['required', 'min:8',
'regex: // some long long regex'
],
// message
[
$passwordName.".regex" => "Your new password must be more than 8 characters long, should contain at-least 1 uppercase, 1 lowercase, 1 numeric and 1 special character.",
]
);
}
// Usr Id is by itself as it might be optional in registering.
public function validateNewUsrId(Request $request, $userIdName) {
$request->validate([
$userIdName => 'required|unique:users',
]);
}
And I can then use this repository easily like this in my controller.
$this->userRepository->validateNewEmail($request, "email");
$this->userRepository->validateNewPassword($request, "password");
$this->userRepository->validateNewUsrId($request, "usr_id");
The reason is because there might be multiple controllers that use the same rules, thus putting them in one place is better
However, I realised that this method does not work because it returns the first error only. For example when both the email and password is wrong, only the email error gets returned to the frontend.
What is the best way to achieve what I want? I want to put all my validation/rules in one place to be reused.
My first solution is this: Each function returns the error MessageBag which is then joined together. I will use return $validator->errors(); to return the MessageBag which can be found here https://laravel.com/docs/8.x/validation#retrieving-the-first-error-message-for-a-field
However I slightly dislike it because then in order to check for whether an error occured, I would need to check if MessageBag is empty and then throw an error which seems a little weird.
The other way I thought of is to return the rules instead, so that I can join them in my controller and then validate all in one go. This seems better but I have to combine the error messages as well, which can be a little tricky if there are multiple (since the key is not fixed, see the code $passwordName.".regex" for example.), as I will need to update the key to each message.
The best way for me, is if I could return a validator for each function, and then use some sort of Validate::ValidateAll function? Is that possible?
How is this implemented usually?
Modern Laravel applications typically use form request validation. With this approach, Laravel handles all the validation and returns error messages automatically. Simply write your form request class, and then use it in place of Request in your controller methods:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rules\Password;
class MyFormRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*/
public function rules(): array
{
return [
'email' => ['required', 'email', 'unique:users'],
'password' => [
'required',
Password::min(8)->mixedCase()->numbers()->symbols()
],
'usrid' => ['required', 'unique:users'],
];
}
}
public method store(MyFormRequest $request)
{
// $request has been validated, no further checking needed
}
Note I'm using Laravel's built-in password validation rules instead of relying on a "long long regex."

Which condition i need for laravel validation if i need to check max strlen just for numbers from a string which contains comma and dot

I have this situation:
An input which can contain max chars 11 ( e.g. 12345678.00 ) 10 numbers and 1 comma or dot.
I need to check only if max strlen of numbers is grater than 10, for example user cannot insert this number 12345678901. This input is for price.
So, i use laravel framework and in my function at the beggining i already extracted the max strlen value of numbers of that input but i don't know how to put in laravel condition.
My function:
$price = (int) filter_var($request->price, FILTER_SANITIZE_NUMBER_INT);
$max = strlen($price);
$this->validate($request,
//rules for input validation
[
'price' => ??
],
//message for input validation
[
'price.??' => 'Some text error'
]);
If exist another way to verify the condition in php and send the message please tell me. For clarifying i cannot use numeric number, or max|min condition..
Best regards,
You have to create a custom validator. For that you can follow this blog. https://laraveldaily.com/how-to-create-custom-validation-rules-laravel
Or Create a validator class by running
php artisan make:rule StrDigitCalculator
This will create a class in App\Rules folder. Open App\Rules\StrDigitCalculator.php and paste code below so your custom validator will look like this
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class StrDigitCalculator implements Rule
{
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
$int = (int) filter_var($value, FILTER_SANITIZE_NUMBER_INT);
return strlen($int) == 10 : true : false;
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
// Your custom message for this validation
return 'Validation Fails';
}
}

How to remove item from request class Laravel

I want to remove slug from $request when I'm updating record and new slug equals to old slug! (Because I use $request->validate() to check if slug is unique in table but it fails!)
You can do that without removing the field. For example, if you're using validation request, you can ignore the unique-checking like this:
// don't forget to use this in the top of your class-file
use Illuminate\Validation\Rule;
public function rules()
{
// for your case replace the word "post"s if need for your appropriate table
return [
'slug' => ['required', Rule::unique('posts')->ignore($this->post()->id)]
];
}
I found the solution! we can use $requst->requst->remove('slug');

Validating array request in Laravel

I have a dynamically generated form. I use an array to retrieve all the data. Something like this:
<input type="text" class="dynamically-generated" name="ItemArray[]">
<!-- This code as many times as desired -->
Now I want these inputs to be validated in the request:
public function rules()
{
return [
'Item' => 'integer'
];
}
I need however to do this in each of the elements in the array. This would be pretty easy in plain PHP. How is this possible in Laravel? I want to do this properly
You're more than likely going to validate these inputs before storing them. So you could something like the following.
/**
* Store a new something.
*
* #param Request $request
* #return Response
*/
public function store(Request $request)
{
$this->validate($request, [
'item' => 'required|max:255'
]);
// The something is valid, store in database...
}
The one you are using above is for complex validation scenarios.
You can read more on Validation in Laravel here

Conditional validation of fields based on other field value in Symfony2

So here is the scenario: I have a radio button group. Based on their value, I should or shouldn't validate other three fields (are they blank, do they contain numbers, etc).
Can I pass all these values to a constraint somehow, and compare them there?
Or a callback directly in the controller is a better way to solve this?
Generally, what is the best practice in this case?
I suggest you to use a callback validator.
For example, in your entity class:
<?php
use Symfony\Component\Validator\Constraints as Assert;
/**
* #Assert\Callback(methods={"myValidation"})
*/
class Setting {
public function myValidation(ExecutionContextInterface $context)
{
if (
$this->getRadioSelection() == '1' // RADIO SELECT EXAMPLE
&&
( // CHECK OTHER PARAMS
$this->getFiled1() == null
)
)
{
$context->addViolation('mandatory params');
}
// put some other validation rule here
}
}
Otherwise you can build your own custom validator as described here.
Let me know you need more info.
Hope this helps.
You need to use validation groups. This allows you to validate an object against only some constraints on that class. More information can be found in the Symfony2 documentation http://symfony.com/doc/current/book/validation.html#validation-groups and also http://symfony.com/doc/current/book/forms.html#validation-groups
In the form, you can define a method called setDefaultOptions, that should look something like this:
public function buildForm(FormBuilderInterface $builder, array $options)
{
// some other code here ...
$builder->add('SOME_FIELD', 'password', array(
'constraints' => array(
new NotBlank(array(
'message' => 'Password is required',
'groups' => array('SOME_OTHER_VALIDATION_GROUP'),
)),
)
))
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'validation_groups' => function (FormInterface $form) {
$groups = array('Default');
$data = $form->getData();
if ($data['SOME_OTHER_FIELD']) { // then we want password to be required
$groups[] = 'SOME_OTHER_VALIDATION_GROUP';
}
return $groups;
}
));
}
The following link provides a detailed example of how you can make use them http://web.archive.org/web/20161119202935/http://marcjuch.li:80/blog/2013/04/21/how-to-use-validation-groups-in-symfony/.
Hope this helps!
For anyone that may still care, whilst a callback validator is perfectly acceptable for simpler dependencies an expression validator is shorter to implement.
For example if you've got a field called "Want a drink?" then if yes (true) "How many?" (integer), you could simplify this with:
/**
* #var bool|null $wantDrink
* #ORM\Column(name="want_drink", type="boolean", nullable=true)
* #Assert\NotNull()
* #Assert\Type(type="boolean")
*/
private $wantDrink;
/**
* #var int|null $howManyDrinks
* #ORM\Column(name="how_many_drinks", type="integer", nullable=true)
* #Assert\Type(type="int")
* #Assert\Expression(
* "true !== this.getWantDrink() or (null !== this.getHowManyDrinks() and this.getHowManyDrinks() >= 1)",
* message="This value should not be null."
* )
*/
private $howManyDrinks;
You write the expression in PASS context, so the above is saying that $howManyDrinks must be a non-null integer at least 1 if $wantDrink is true, otherwise we don't care about $howManyDrinks. Make use of the expression syntax, which is sufficient for a broad range of scenarios.
Another scenario I find myself frequently using a expression validator are when I've got two fields to the effect of "date start" and "date end", so that they can each ensure that they are the right way around (so that the start date is before or equal to the end date and the end date is greater or equal to the start date).

Categories