Arvind K.
Arvind K.

Reputation: 1294

CakePHP 3.5 how to validate an empty or not empty field based on the value of another field?

I am using CakePHP 3.5.5.

I am struck with a custom validation rule. I have country and state fields in my view. In case if the value of country field is US then we make state field required otherwise we don't. I have put a custom validation rule in my UsersTable.php like this:

public function validationDefault(Validator $validator) {
  $validator
    ->add('state', 'custom', [
    'rule' => [$this,'validate_state'],
    'provider' => 'custom',
    'message' => 'Please enter state'
  ]);
}

and have created validate_state function like this:

public function validate_state($value, $context) {
    //debug($value, $context);die;
//if state is us)
  //if state is not empty return true;
  //if state is empty return false;
//else return true;
}

But it not working at all. The only thing it is doing is showing the "This field cannot be left empty" message if I use this rule. I understand that CakePHP assumes to run notEmpty on its own if you have created a validator rule for a field. But my problem is I cannot rule field value true or false before checking the value of another field for which I need to use custom function before checking the notEmpty method. But in my case here if I dont use notEmpty method it neither is entering the custom function validate_state nor it is showing the custom message i use in this rule.

Do you know a better way to do it without hacking the form request data before sending it to validator?

Upvotes: 0

Views: 1980

Answers (1)

ndm
ndm

Reputation: 60453

Use a callable for the notEmpty (or allowEmpty) rule, and just like you'd do it in your custom rule, evaluate the context to determine whether the rules applies (ie whether the field must not be empty), something along the lines of:

$validator
    ->notEmpty('state', null, function ($context) {
        // field must not be empty when the conditions evaluate to true
        return
            isset($context['data']['country']) &&
            $context['data']['country'] === 'US';
    })
    // ...

See also

Upvotes: 1

Related Questions