trilipio
(Trilipio)
June 2, 2013, 6:11pm
1
Hello,
what is the best way of using validation rules: Just for updat.ing things in the db or also for getting records?
For example: You want to get a specific entry from your database and check the given parameter.
Would you create a rule for it:
...
array('val', 'required'),
array('val', 'length', 'min'=>3),
array('val', 'exists')
...
$model->val = $_GET['val'];
if($model->validate()) {
//do search
}
or do that without a validator by checking the variable in the controller:
if(isset($_GET['val']) && length($_GET['val'])>3...) {
//do search
}
//EDIT: You know, upda.ting is a spam word, because it contains da.ting
konapaz
(Konapaz)
June 2, 2013, 6:35pm
2
Hi trilipio.
According to Yii and MVC architectural the best way is using validators in Model
http://www.yiiframework.com/wiki/56/
Even you want more complex validator you could create one by yourself
http://www.yiiframework.com/wiki/168/create-your-own-validation-rule/
trilipio
(Trilipio)
June 2, 2013, 7:39pm
3
So you whoud do something like this?
$model = new Mymodel("searchtitle");
$model->title = $_GET['title'];
if($model->validate()) {
$model = Mymodel->find("title=?", array($model->title));
}
Tsunami
(Erik)
June 2, 2013, 8:32pm
4
No, you wouldn’t. Why do you want to validate when you select records? You only need validation when inserting or updating.
trilipio
(Trilipio)
June 3, 2013, 3:29am
5
Okay, so you use validation rules only for updat.ing/saving data and if you want to validate other User input e.g. for a select, you use normal php methods?
But Take a look at the auto-generated code of a model. Dont they use validation rules for the search method, which is clearly Not a upda.te/insert operation?
konapaz
(Konapaz)
June 3, 2013, 9:16am
6
trilipio:
Okay, so you use validation rules only for updat.ing/saving data and if you want to validate other User input e.g. for a select, you use normal php methods?
Yes you have to use validate when insert or update a record of Model but you can use it in other cases like your (but is not nessasary because find method with params is secured)
if($model->validate()) { //you can ommits the validation
$model = Mymodel->find("title=?", array($model->title));
}
But Take a look at the auto-generated code of a model. Dont they use validation rules for the search method, which is clearly Not a upda.te/insert operation?
In search case, It is no nessesary to validate the user inputs because Yii Framework with code like that
$criteria = new CDbCriteria;
$criteria->compare('id', $this->id);
manipulates secured compares.