Customize message in requirePresence validation

Hi there,

i can’t customize my message in requirePresence Validation:

$validator->requirePresence([
   'user_id' => [
       'mode' => 'create',
       'message' => 'My custom message.',
   ]
]);
        
$validator->requirePresence('user_id', 'create', __('My custom message')); 

Both examples generate the following message:
“This field cannot be left empty”

What is the contents of the array of data you are validating when you get ‘This field cannot be left empty’?

I found with just requirePresence if user_id is NOT in the validation array you get the custom message

   $validator = new Validator();

   $validator
            ->requirePresence(['user_id' => [
                'message' => 'My custom message.'
            ]]);

   $data = ['no_user_id' => ''];

   $result = $validator->validate($data);

   dd($result);
// $result
[
  'user_id' => [
    '_required' => 'My custom message.'
  ]
]

If user_id is present and null it seems to return the message from a different validation rule you get ‘This field cannot be left empty’

 $data = ['user_id' => null];

 $result = $validator->validate($data);

// result

[
  'user_id' => [
    '_empty' => 'This field cannot be left empty'
  ]
]

When allowEmptyString is added with requirePresence it passes validation:

  $validator
            ->requirePresence(['user_id' => [
                'message' => 'My custom message.'
            ]])
            ->allowEmptyString('user_id');

    $data = ['user_id' => null];

  $result = $validator->validate($data);

  dd($result);
// $result
[]

This field cannot be left empty is the default message for the “not empty” validation.

So you are getting this message because the user_id field is present in the POST data but is empty.

1 Like

okay thanks. That makes sense…