0

I am using Yii 2.0, I can't figure out how to validate the value of the selected option in the drop-down list, I need to check, if its greater than ZERO.

What i have so far

in the Rules array

['year', 'required'],
['day', 'required'],
['month', 'checkDefaultValue'],...

The custom validate method is

public function checkDefaultValue() {
    if ($this->month > 0) {
        $this->addError('month', 'Month error message...');
    }
}

This code isn't working, is there a better way for doing it?

1
  • your array is like ["Jan", "Feb"] OR [0=>JAN, 1=> "Feb"] Commented Jun 10, 2014 at 10:02

3 Answers 3

2

You can do something like this

['month', 'in','range' => ['Jan','Feb']],

Specify the range in which the values should be.

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

1 Comment

Thanks, its working, but what if i need to create a condition like != or something similar?
0

Your code is not working because it adds the error if the month is greater than zero, which is the opposite of what you want.
This would work:

public function checkDefaultValue() {
    if ($this->month <= 0) {
        $this->addError('month', 'Month error message...');
    }
}

Or use the default number validator to do that and even more:

[
    ['month'], 
    'number', 
    'integerOnly' => true,
    'min' => 1,
    'tooSmall'=>'the selected item is too small for month!!!',
    'max' => 12,
    'tooBig'=>'the selected item is too big for month!!!',
]

Comments

0

You can use range validator, if you still want to do a custom validation this will help you.

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.