1

I'm using Cakephp (v3.0). I have got a field "num_max_intents" that I want that only takes values greater than 0 and also I want that "date" field be greater than actual date.. My validationDefault() code is the next:

public function validationDefault(Validator $validator){
    $validator->notEmpty('num_max_intents')
              ->notEmpty('package')
              ->notEmpty('date');
    return $validator;
}

What's the simplest way to do this?

3 Answers 3

1

For a simple solution, use a range validator:

$validator->add(
    'num_max_intents', 
    'valid', 
    ['rule' => ['range', 0, PHP_INT_MAX]]
);

This validator requires both the lower and upper limit to be set, so you have to use some value here. You can find all validators in Cake\Validation\Validation.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use a closure as a custom validation rule. Just remember to return true if the rule validates and false if it fails. For example, to check the date field is greater than the current date:-

public function validationDefault(Validator $validator){
    $validator
        ->add('date', 'valid', ['rule' => function ($value) {
            return $value > date('Y-m-d');
        }]);
    return $validator;
}

Comments

0

To validate "date" field I'm using this code:

public function validationDefault(Validator $validator){
    $validator->add('date', 
                    'valid', [
                        'rule' => function ($value) {
                            return $value > date('Y-m-d'); },
                        'message' => 'Invalid date.'
                    ]
              )
              ->notEmpty('date');
    return $validator;
}

But when I select a date less than actual date on my form, the validator doesn't run correctly and doesn't show the error message... What's wrong?

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.