0

I extedned request class to create my own valdiation rules. In that class I added my custom validation function. In function I check if tags are pass regEx and I would like to filter tags to remove tags shorter then 2 characters.

And later keep in request only tags that passed validation.

    public function createPost(PostRequest $request)
{
    dd($request->all()); //In this place I would like to keep only tags passed through validation not all tags recived in request
}

Is it possibile to do it? How to set it in Request class?

'tags' => [
            'nullable',
            'string',
            function ($attribute, $value, $fail){
                $tagsArray = explode(',', $value);
                if(count($tagsArray) > 5) {
                    $fail(__('place.tags_max_limit'));
                }

                $tagsFiltered = [];
                foreach ($tagsArray as $tag){
                    $tag = trim($tag);
                    if(preg_match('/^[a-zA-Z]+$/',$tag)){
                        $tagsFiltered[] = $tag;
                    };
                }

                return $tagsFiltered;
            }
        ],

EDIT: I think we miss understanding. I would like to after validation have only tags that returned in variable $tagsFiltered; Not the same as recived in input.

Klick
  • 1,418
  • 1
  • 23
  • 45

2 Answers2

0

You have to create this custom regex rule and use it into rules() function.

Like so:

public function rules()
{
    return [
        'tag' => 'regex:/[^]{2,}/'
    ];
}

public function createPost(PostRequest $request)
{
    $request->validated();
}

And then just call it via validated() function wherever you want.

Lucas Arbex
  • 889
  • 1
  • 7
  • 15
-1

first define validation rule with this command:

php artisan make:rule TagsFilter

navigate to TagsFilter rule file and define your filter on passes method:

   public function passes($attribute, $value)
    {
                $tagsArray = explode(',', $value);
                $tagsFiltered = [];
                foreach ($tagsArray as $tag){
                    $tag = trim($tag);
                    if(preg_match('/^[a-zA-Z]+$/',$tag)){
                        $tagsFiltered[] = $tag;
                    };
                }

        return count($tagsArray) > 5 && count($tagsFiltered) > 0;
    }

then include your rule in your validation on controller:

$request->validate([
    'tags' => ['required', new TagsFilter],
]);
Ahmed Atoui
  • 1,506
  • 1
  • 8
  • 11