Yii 2.0: Model validation for field ranges using yii2-field-range extension

29 followers

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:

Scenario 1: Field 1 should not equal Field 2

As mentioned in the first example in the extension demo site, let's say 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. Setup the following 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.

Scenario 2: Attribute 2 cannot be less than Attribute 1

As mentioned in the second example in the extension demo site, let's say 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 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.

Be the first person to leave a comment

Please to leave your comment.

Write new article