7

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?

0

5 Answers 5

10

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

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

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.

1
  • I tried the proposed "Honeypot spam prevention" and it has everything you need. ;-)
    – creg
    Commented Nov 11, 2017 at 7:06
2

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

return [
   'emptyInputField' => 'prohibited',
];
1
  • 1
    I had to use 'emptyInputField' => 'nullable|prohibited',, as otherwise the rule always triggered, even if an empty string was sent. Commented Jan 31, 2023 at 10:48
0

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.

1
  • That's not what the OP asked for.. the field always has to be empty..
    – Martijn
    Commented Jan 4, 2020 at 9:33
-1

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

1
  • 1
    Links to external resources are encouraged, but please add context around the link so your fellow users will have some idea what it is and why it’s there. Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline.
    – pableiros
    Commented Aug 21, 2016 at 23:07

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