How do I fix user input before validating / saving?

My form has a field for the price which will be stored in decimal format in db.

Now if the user enters commas " , " does not specify " . ", How can I safely replace it so that it is saved correctly? for example, instead of 12,34

, will be saved 12.34

and not12.00

+3


source to share


1 answer


It would probably be easier if you used CFilterValidator

to automatically convert the input from a string to a float when validation occurs; the rest must take care of themselves.

So your model would have

public function rules() {
    return array(
        array('price', 'filter', 'filter' => 'convertToFloat'),
    );
}

      

and the filter function will look like



function convertToFloat($value) {
    return floatval(trim(str_replace(',', '.', $value)));
}

      

You can also specify the filtering function as any valid callable , for example make it a model method and specify it as

'filter' => array($this, 'convertToFloat')

      

+8


source







All Articles