snubbus
snubbus

Reputation: 387

Check if a string is "0" with Laravel validation

How can I check if a value of a string is "0" in Laravel 5.3?

Here's my validation rules before processing the data:

// I want them to be anything but "0". So "01", "1" etc. are all okay
$rules = [
    'state' => 'required',
    'city' => 'required',
];

As the data is passed as strings I cannot use min:1 for this.

I'm sorry if this have already been asked, but I cannot find an answer. Many thanks!

Upvotes: 8

Views: 18415

Answers (3)

Akbarali
Akbarali

Reputation: 904

I needed to check if the price is greater than 0. This method helped me.

Laravel Doc: gt:field

'buy_price'  => 'required|integer|gt:0',
'sell_price' => 'required|integer|gt:buy_price',

Error: "The buy price field must be greater than 0. (and 1 more error)"

Upvotes: 0

snubbus
snubbus

Reputation: 387

This worked for me:

$rules = [
    'state' => 'required|not_in:0',
    'city' => 'required|not_in:0',
];

Also, have a look at this: Laravel 5.2 validation check if value is not equal to a variable

Upvotes: 15

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26278

In that case you can use regex like:

$rules = array(
    'field'=> 'regex:/(^[A-Za-z0-9 ]+$)+/'
);

regex:pattern

The field under validation must match the given regular expression.

Note: When using the regex pattern, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.

Refrence

Upvotes: 0

Related Questions