Karl
Karl

Reputation: 5463

Laravel Form Validation, fail if not empty

I have an input field which needs to be empty, otherwise I want the validation to fail. This is an attempt at stopping spam through a contact form.

I've looked at the documentation for the validation but there's nothing to do this, other than the "max" rule, but this doesn't work.

Any other options?

Upvotes: 7

Views: 6330

Answers (5)

Farzan Badakhshan
Farzan Badakhshan

Reputation: 403

For Laravel 8.x and above, you may use the prohibited validation rule:

return [
   'emptyInputField' => 'prohibited',
];

Upvotes: 2

Alauddin Ahmed
Alauddin Ahmed

Reputation: 1185

In laravel 5.8 you can use sometimes for conditional rules adding. 'email' => 'sometimes|email' . This rules will be applied if there is something present in input field.

Upvotes: 0

hktang
hktang

Reputation: 1833

Here's a clean and (probably) bullet-proof solution:

    'mustBeEmpty'  => 'present|max:0',

Upvotes: 10

Slava
Slava

Reputation: 1

You can use the empty rule. Details can be seen here: https://laravel.com/docs/5.2/validation#conditionally-adding-rules

Upvotes: -1

The Alpha
The Alpha

Reputation: 146201

In the method where you are validation, extend/add custom rule:

Validator::extend('mustBeEmpty', function($attr, $value, $params){
    if(!empty($attr)) return false;
    return true;
});

Then you may use this rule like:

protected $rules = array(
    'emptyInputField' => 'mustBeEmpty'
);

Then everything is as usual, just use:

$v = Validator::make(Input::except('_token'), $rules);
if($v->passes()) {
    // Passed, means that the emptyInputField is empty
}

There are other ways to do it without extending it like this or extending the Validator class but it's an easy Laravelish way to do it. Btw, there is a package available on Github as Honeypot spam prevention for Laravel applications, you may check that.

Upvotes: 3

Related Questions