I’m new to Yii framework. I 'm using Yii framework for my application. Now , the data is extracted from XML file and not from database.The data entered into textfield is also converted to XML file. The model class extends CFormModel . I have a textfield that should allow only integers. I did a front end validation using Javascript that works fine for some browsers but not most. So, I want to do a backend validation using rules(). How can I write the validation rule for this to allow integers.
Add this rule to model
public function rules()
{
return array(
array('attributename','numerical','integerOnly'=>true),
);
}
laqrhead
(Joel)
December 6, 2013, 10:23pm
4
I think you may need to turn on ajax or client validation.
View:
<?php $form=$this->beginWidget('CActiveForm', array(
'enableAjaxValidation'=>true,
)); ?>
Controller:
public function actionUpdate($id)
{
$model=$this->loadModel($id);
$this->performAjaxValidation($model);
if(isset($_POST['MyModel']))
{
$model->attributes=$_POST['MyModel'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}
Add also to actionCreate
or for client side:
View:
<?php $form=$this->beginWidget('CActiveForm', array(
'enableClientValidation'=>true,
)); ?>
Rick_39_s
(Rick's)
December 7, 2013, 10:36am
5
to use validations of a model, I think you need ACTIVE form/model insteal of formModel.
ineersa
(Ineersa)
December 7, 2013, 9:34pm
7
You can do validations even without an actuall model. You’ll need to make dummy for validations. As example:
class MyValidator extends CFormModel {
public function __get($name) {
return isset($_POST[$name])?$_POST[$name]:null;
}
static function myValidate( Array $rules ) {
$dummy = new MyValidator();
foreach($rules as $rule) {
if( isset($rule[0],$rule[1]) ) {
$validator = CValidator::createValidator(
$rule[1],
$dummy,
$rule[0],
array_slice($rule,2)
);
$validator->validate($dummy);
}
else { /* throw error; */ }
}
//print_r( $dummy->getErrors() );
return !$dummy->hasErrors();
}
}
//use of this
$rules = array(
array('name, email', 'required'),
array('email', 'email'),
);
if( MyValidator::myValidate($rules) ) {
....
}
For this, just put your attributes to validate in $_POST.