B
B
BonBon Slick2017-05-04 12:47:38
Laravel
BonBon Slick, 2017-05-04 12:47:38

Validation of a field that can be either a string or an integer?

if (!is_numeric($request->get('search_text'))) {
            $this->validate($request, [
                'search_text' => 'required|filled|string|min:1|max:55|',
            ]);
        } else {
            $this->validate($request, [
                'search_text' => 'required|filled|integer|min:1|max:55|',
            ]);
        }

You cannot add string|integer . And if you send in the query where id == '9' PostgreSQL gives an error. There is no such thing in Mysql, it itself leads to the desired type there, and yet. The query can be where title == 9 , must be converted to (string).
So what's the best way to validate a field that can be either int or str?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
B
BonBon Slick, 2017-05-04
@BonBonSlick

$this->validate($request, [
                'type' => 'required|filled|string|min:2|max:15|',
                'order' => 'required|filled|string|min:3|max:4|',
                'search_text' => 'required|filled|string|min:1|max:55|',
            ]);

Post::whereRaw("CAST(id AS TEXT) ILIKE '%$search_text%'")->get()

M
Maxim Khodyrev, 2017-05-04
@maximkou

Validate always as a string, and pass the value cast to the required type into the query.

$this->validate($request, [
    'search_text' => 'required|filled|string|max:55',
]);

if (preg_match('/^\d+$/', $search)) {
    // find_by_id ((int)$search)
} else {
   // find_by_name ($search)
}

Well, the min rule is redundant here, because there are required and filled rules.

A
Alexey Ukolov, 2017-05-04
@alexey-m-ukolov

It is necessary not to edit the validation, but to bring the line to the integer before using it.
The validation rule 'integer'will pass and 42and '42', and the rule string|min:1|max:55is a string from 1 to 55 characters long.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question