8

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!

2
  • Clear more by giving example, which input will be ok and which is not ? Commented Mar 18, 2017 at 9:54
  • Anything but "0" will be okay, so "01", "1", "abc" etc should all be allowed
    – snubbus
    Commented Mar 19, 2017 at 14:39

3 Answers 3

15

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

1
  • Be careful of unintended behavior from lax type comparison. not_in uses PHP's in_array() with $strict = false. This causes unexpected rule failures, e.g. city = "1E-1" would fail validation because (int) "1E-1" = 0
    – Andy White
    Commented Aug 5, 2020 at 13:15
0

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

1
  • thanks for the reply, I've looked into regex, what would the pattern be to disallow "0" in this case? Anything other than the string "0" should pass the validation.
    – snubbus
    Commented Mar 19, 2017 at 14:41
0

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)"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.