Q:

format html input with thousand separator with Yii - jquery

So I have these rule in a model in Yii:
array('svalue','numerical'),

As these are numbers (and later they will be used for calculations),
I'd like to save it as number.
The client though is asking that numbers be formatted with a comma ',' separator for thousands (1,200 = thousand two hundred). My predecessor on the project used
$.fn.digits = function(){
    return this.each(function(){
        $(this).keyup(function(){
            $(this).val( $(this).val().replace(/,/g,"").replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") );
        });
    })
}

and I added keydown features so that you can't put any other characters than numbers.
Unfortunately now, the jquery.digits() function correctly formats any number to thousands - but yii apparently generates some codes, and then on form validation it says 
"svalue must be a number".
How can I have both functions, to have a formatted string like the clients wants and to have still a numerical check on the Yii backend?

A:

Use str_replace before saving or validating the model:
In model's beforeValidate():
protected function beforeValidate() {
    if(parent::beforeValidate) {
        $this->svalue = str_replace(',', '', $this->svalue);
        return true;
    }
    return false;
}

Or in controller's save and update actions:
$model->attributes = $_POST['Modelname'];
$model->svalue = str_replace(',', '', $model->svalue);

But the best way to do this will be on the client-side (actually view file) itself, change the value back to number before form submit, and whenever the form is displayed, add the commas.
When form is displayed, add commas for values already stored (update scenario or partially validated scenario):
$("#field").val( $("#field").val().replace(/,/g,"").replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") );

For newly entered values, you already have your function to add commas.
Then before submitting the form, change the value back to one without commas:
$("#form-selector").submit(function(){
    $("#field").val( $("#field").val().replace(/,/g,"") );
    return true; // let the form submit
});

Since this is purely a presentation change i think the manipulation should be in the client-side. 

