Karl
Karl

Reputation: 410

Cake PHP validation, change incoming $data

I got a problem with my cake validation. The user enters e.g. "20€" in a form field and I only want to get the number "20" with stripped out Euro-sign. But the validation methods only allow checking if something is what it´s supposed to be.

I´m about to create a function in my rule-set but I´m struggling going further because what the function returns in cake context is either true or false, not a modified variable like I need ...

'rule-3' => array(
    'rule'    => 'checkEuro',
    'message' => 'don´t need one because it should be a conversion only :-('
)

public function checkEuro($data) {
    $data = str_replace('€','',$data);
    return preg_replace('/[^0-9]/','', html_entity_decode($data));
}

I hope you can help. Thanks in advance

Upvotes: 0

Views: 478

Answers (1)

thaJeztah
thaJeztah

Reputation: 29077

If you only need to store the amount itself inside the database and not the euro-sign, you should strip the Euro-sign before validating.

You can do this inside the beforeValidate() callback of your model;

public function beforeValidate(array $options = array())
{
    if (!empty($this->data[$this->alias]['FIELDNAME']) {
        // Strip the euro-sign
        // NOTE: should also take plain, non-entity € into account here?
        $this->data[$this->alias]['FIELDNAME'] = str_replace(
            '€', '', $this->data[$this->alias]['FIELDNAME']
        );
    }

    return parent::beforeValidate($options);
}

(Of course, replace FIELDNAME with the actual fieldname)

After stripping the currency-symbol, validate the value using the decimal or numeric validation rule

note If you do want to store the value including the currency-symbol, use the core money validation rule.

Upvotes: 3

Related Questions