Model range validation along with yii2-field-range extension

The yii2-field-range extension enables you to easily setup ActiveField range fields with Bootstrap styling. You basically can setup two attributes joined together like a single field with combined validation error block.

Here are a few tips on configuring model validation rules for your two attributes using this extension:

Validation Scenario 1: Field 1 should not equal Field 2

Let’s consider the first example on the extension demo site. You have two attributes configured with a dropDownList named start_place and end_place. Your start_place and end_place should not be same when selected either way. In order to do this, setup the following validation rules in your model:

public function rules() {
    return [
        [
            ['start_place'], 
            'compare', 
            'compareAttribute'=>'end_place', 
            'operator'=>'!=', 'skipOnEmpty'=>true
        ],
        [
            ['end_place'], 
            'compare', 
            'compareAttribute'=>'start_place', 
            'operator'=>'!='
        ],
    ];
}

As seen, the skipOnEmpty for start_place allows the validation to be deferred until end_place is entered.

Validation Scenario 2: Attribute 2 cannot be less than Attribute 1

Similarly, let’s look at the second example in the extension demo site. You have two attributes configured: from_amount and to_amount. For this scenario, let’s say following rules are needed:

  • Both amounts are required
  • Both amounts must be numeric/decimals.
  • Both amounts cannot exceed zero.
  • The to_amount cannot be less than from_amount.

To achieve all of the above, setup the following validation rules in your model:

public function rules() {
    return [
        [['from_amount', 'to_amount'], 'required'],
        [['from_amount', 'to_amount'], 'double', 'min'=>0],
        [
            ['from_amount'], 
            'compare', 
            'compareAttribute'=>'to_amount', 
            'operator'=>'<=', 
            'skipOnEmpty'=>true
        ],
        [
            ['to_amount'], 
            'compare', 
            'compareAttribute'=>'from_amount', 
            'operator'=>'>='
        ],
    ];
}

Hope that helps. Enjoy using the extension. If you found other interesting ways of using the yii2-field-range extension OR used other validation rules, it would be nice to share your experience.