How can i validate url in Yii - yii

I have a form in Yii.
It have model Validation.
In that form I have to insert url in textfield.
eg:https://www.google.co.in
In database I kept fields as varchar.
Rules in model are
public function rules() {
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('url', 'required'),
array('name, url', 'length', 'max' => 255),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('name, url', 'safe', 'on' => 'search'),
);
}
How can I keep validation for this in Model?

Try This:-
return array(
array('yoururl', 'required'),
array('yoururl', 'url'),//for url validation
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('name, yoururl', 'safe', 'on' => 'search'),
):

array('inputURL', 'url')
and if you want to add http in front if missing use
array('website', 'url',defaultScheme' => 'http')

You should use url validator
this way array('siteurl', 'url'),
public function rules() {
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('url', 'required'),
array('name, url', 'length', 'max' => 255),
array('url', 'url'),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('name, url', 'safe', 'on' => 'search'),
);
}

Related

yii user and rights- admin can not access any page

Fatal error: Call to undefined method Rights::t()
Getting this error when ever i want to go in any controller or in any controller's action. I am using yii user and rights. for instance when i type localhost/business/address/create i get the above error.
Yii user is working fine, even rights too. But i cannot access any controller.
'bootstrap',
'basePath'=>dirname(FILE).DIRECTORY_SEPARATOR.'..',
'name'=>'My Web Application',
// preloading 'log' component
'preload'=>array('log'),
'aliases' => array(
'bootstrap' => 'ext.bootstrap' ),
// autoloading model and component classes
'import'=>array(
//addedd these lines
'application.modules.user.models.*',
'application.modules.user.components.*',
'application.modules.rights.*',
'application.modules.rights.components.*',
'application.models.*',
'application.components.*',
'bootstrap.behaviors.*',
'bootstrap.helpers.*',
'bootstrap.widgets.*'
),
'modules'=>array(
// uncomment the following to enable the Gii tool
'gii'=>array(
'class'=>'system.gii.GiiModule',
'password'=>'centangle',
'generatorPaths' => array( 'bootstrap.gii', ),
// If removed, Gii defaults to localhost only. Edit carefully to taste.
'ipFilters'=>array('127.0.0.1','::1'),
),
'user'=>array(
'tableUsers' => 'user',
'tableProfiles' => 'profiles',
'tableProfileFields' => 'profiles_fields',
# encrypting method (php hash function)
'hash' => 'md5',
# send activation email
'sendActivationMail' => true,
# allow access for non-activated users
'loginNotActiv' => false,
# activate user on registration (only sendActivationMail = false)
'activeAfterRegister' => false,
# automatically login from registration
'autoLogin' => true,
# registration path
'registrationUrl' => array('/user/registration'),
# recovery password path
'recoveryUrl' => array('/user/recovery'),
# login form path
'loginUrl' => array('/user/login'),
# page after login
'returnUrl' => array('/user/profile'),
# page after logout
'returnLogoutUrl' => array('/user/login'),
),
'rights'=>array(
'install'=>true,
'superuserName'=>'admin', // Name of the role with super user privileges.
'authenticatedName'=>'Authenticated', // Name of the authenticated user role.
'userIdColumn'=>'id', // Name of the user id column in the database.
'userNameColumn'=>'username', // Name of the user name column in the database.
'enableBizRule'=>true, // Whether to enable authorization item business rules.
'enableBizRuleData'=>true, // Whether to enable data for business rules.
'displayDescription'=>true, // Whether to use item description instead of name.
'flashSuccessKey'=>'RightsSuccess', // Key to use for setting success flash messages.
'flashErrorKey'=>'RightsError', // Key to use for setting error flash messages.
'baseUrl'=>'/rights', // Base URL for Rights. Change if module is nested.
'layout'=>'rights.views.layouts.main', // Layout to use for displaying Rights.
'appLayout'=>'application.views.layouts.main', // Application layout.
'cssFile'=>'rights.css', // Style sheet file to use for Rights.
'install'=>false, // Whether to enable installer.
'debug'=>false,
),
),
// application components
'components'=>array(
'user'=>array(
'class'=>'WebUser',
// enable cookie-based authentication
'allowAutoLogin'=>true,
'loginUrl'=>array('/user/login'),
),
'authManager'=>array(
'class'=>'RDbAuthManager',
'connectionID'=>'db',
'itemTable'=>'authitem',
'itemChildTable'=>'authitemchild',
'assignmentTable'=>'authassignment',
'rightsTable'=>'rights',
'defaultRoles'=>array('Authenticated', 'Guest'),
),
'bootstrap' => array(
'class' => 'bootstrap.components.BsApi', ),
// uncomment the following to enable URLs in path-format
'urlManager'=>array(
'urlFormat'=>'path',
'showScriptName' => false,
'rules'=>array(
'user/registration/<id:\w+>' => 'user/registration',
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
),
),
/*'db'=>array(
'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
),*/
// uncomment the following to use a MySQL database
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=copy',
'emulatePrepare' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
),
'errorHandler'=>array(
// use 'site/error' action to display errors
'errorAction'=>'site/error',
),
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CFileLogRoute',
'levels'=>'error, warning',
),
// uncomment the following to show log messages on web pages
/*
array(
'class'=>'CWebLogRoute',
),
*/
),
),
),
// application-level parameters that can be accessed
// using Yii::app()->params['paramName']
'params'=>array(
// this is used in contact page
'adminEmail'=>'webmaster#example.com',
),
);
and this is my controller business
class BusinessController extends RController
{
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
'rights',
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('#'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* #param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new Business;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Business']))
{
$model->attributes=$_POST['Business'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Business']))
{
$model->attributes=$_POST['Business'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* #param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('Business');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new Business('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Business']))
$model->attributes=$_GET['Business'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* #param integer $id the ID of the model to be loaded
* #return Business the loaded model
* #throws CHttpException
*/
public function loadModel($id)
{
$model=Business::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* #param Business $model the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='business-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
it is because of this mistake.the problem lies in the writing of the code, make sure you must write your code in config.main like this
'import' => array(
'application.models.*',
'application.components.*',
'bootstrap.behaviors.*',
'bootstrap.helpers.*',
'bootstrap.widgets.*',
//add this code after the above code and thats it, a small stupid mistake may cost you 3 days of hard debugging.
'application.modules.user.models.*',
'application.modules.user.components.*',
'application.modules.rights.*',
'application.modules.rights.components.*'
),

Required Rule on specific condition

I need to apply rule on a form. I have a country and dependent drop down of state.
I need to apply required rule on state field.
But if i choose India from drop down then required rule should be remove from the form.
I have enabled clientsidevalidation true in cactiveform.
View form:
<?php $form = $this->beginWidget('CActiveForm', array(
'id' => 'cart',
'enableAjaxValidation' => false,
'enableClientValidation'=>true,
'clientOptions'=>array('validateOnSubmit'=>true),
// we need the next one for transmission of files in the form.
'htmlOptions' => array('enctype' => 'multipart/form-data'),
));
echo $form->dropDownList($modelUser, 'country', Countries::getcountrylistwithcode(),
array('options' => array($currentCountry=>array('selected'=>true)),
'empty'=>'Select Country',
'class'=>'form-control input-lg',
));
echo $form->error($modelUser,'country');
echo $form->labelEx($modelUser,'state',array('class'=>"col-md-30"));
echo $form->dropDownList($modelUser, 'state', $stateList,array('class'=>"form-control input-lg",'prompt'=>'Select State'));
echo $form->error($modelUser,'state');
$this->endWidget();
?>
And model rules are like this:
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('city,country,state,address_line_one,postcode', 'required'),
You can achieve this by adding a custom rule to your model.
Change your rules function to something like this
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('city,country,address_line_one,postcode', 'required'),
array('state', 'validateState'),
)
}
Next up would be to create the custom validation rule. This would look something like this
public function validateState ($attribute, $params)
{
$aCountriesWithState = array('USA');
if (in_array($this->$attribute, $aCountriesWithState) && empty($this->$attribute))
{
$this->addError($attribute, 'State is missing');
}
}

How display duplicate attribute error validation message in yii

I need display error message when user register end he input email which exist.I try this in my view:
<?php echo $form->errorSummary($model, NULL, NULL, array("class" => "standard-error-summary")); ?>
and this
if($model->hasErrors())
echo CHtml::errorSummary($model);
But it doesn't work.
There is my rules method of User model
public function rules()
{
return array(
array('status', 'numerical', 'integerOnly'=>true),
array('first_name, last_name, email, password', 'length', 'max'=>255),
array('email', 'unique', 'className' => 'User', 'attributeName' => 'email', 'message'=>'This Email is already in use'),
array('id, status, first_name, last_name, email, password', 'safe', 'on'=>'search'),
);
}
RegistrationForm Model:
public function rules()
{
return array(
array('first_name, repeat_password, last_name, password,email', 'required'),
array('email', 'email'),
array('password', 'compare','compareAttribute'=>'repeat_password'),
);
}
and my register action:
public function actionRegister()
{
$model = new RegistrationForm;
if(isset($_POST['RegistrationForm']))
{
$model->attributes = $_POST['RegistrationForm'];
if($model->validate())
{
$user = new User;
$user->first_name = $model->first_name;
$user->last_name = $model->last_name;
$user->password = $model ->password;
$user->email = $model->email;
$user->save();
}
}
$this->render('register',array('model'=>$model));
}
Such as you validate RegistrationForm model, you must have unique rule in it (not onlu in User model). So you can add this rule in your RegistrationForm model too:
public function rules()
{
return array(
array('first_name, repeat_password, last_name, password,email', 'required'),
array('email', 'email'),
// THIS RULE CHECKS EMAIL UNIQUE IN RegistrationForm MODEL
array('email', 'unique', 'className' => 'User', 'attributeName' => 'email', 'message'=>'This Email is already in use'),
array('password', 'compare','compareAttribute'=>'repeat_password'),
);
}
So not not necessary to add custom rule.
Thanks!
I found solution. I added this method in my RegisterationForm Model
public function uniqueEmail($attribute, $params)
{
if($user = User::model()->exists('email=:email',array('email'=>$this->email)))
$this->addError($attribute, 'Email already exists!');
}
and added
array('email', 'uniqueEmail','message'=>'Email already exists!'),
to the rules method

Cannot Update Data When Using Confirm Password (compare rule) in YII model

In the registration form, used password field and confirm password field. After using this data cannot be updated.
Model
public function rules()
{
// NOTE: you should only define rules for those attributes that
return array(
array('name, password', 'required'),
array('password', 'compare', 'compareAttribute'=>'confirm_password'),
array('name', 'length', 'max'=>55),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, name', 'safe', 'on'=>'search'),
);
}
Trying to update user model from index.php
`$post= User::model()->findByPk(1); $post->name='Abcdef'; $post->password='newpassword'; $post->save();`
The new data not updated? when it solve?
The update won't work because the confirmpassword has not been set. If the password is not required on update include a scenario for the password else it will always be checked.
public function rules()
{
// NOTE: you should only define rules for those attributes that
return array(
array('name', 'required'),
array('password', 'required','on'=>'create'),
array('password', 'compare', 'compareAttribute'=>'confirmpassword','on'=>'create'),
array('name', 'length', 'max'=>55),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, name', 'safe', 'on'=>'search'),
);
public $confirmpassword;
public function rules()
{
// NOTE: you should only define rules for those attributes that
return array(
array('name, password, confirmpassword', 'required'),
array('password', 'compare', 'compareAttribute'=>'confirmpassword'),
array('name', 'length', 'max'=>55),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, name', 'safe', 'on'=>'search'),
);
}

How to make email unique in yii user model

validation code is
return array(
array('firstname, lastname, confirm_email, education, email, password, occupation,location , birthdate, interest,gender,created, modified', 'required'),
array('email', 'email'),
array('password', 'length', 'max'=>20, 'min' => 5,'message' => "Incorrect fi (length between 5 and 20 characters)."),
array('firstname', 'match', 'pattern' => '/^[A-Za-z0-9_]+$/u','message' => UserModule::t("Incorrect symbols (A-z0-9).")),
array('email', 'unique'),
);
You may make your email unique in yii user model by the following rule as given in below.
public function rules() {
return array(
...
array('email', 'email'),
array('email', 'unique', 'className' => 'User',
'attributeName' => 'email',
'message'=>'This Email is already in use'),
...
); }
Here className is the name of your user model class, attributeName is your db email field name.
You may also check the below link.
http://www.yiiframework.com/forum/index.php/topic/32786-creating-my-own-model-cmodel-not-cactiverecord/
Thanks
public function rules()
{
return array(
...
array('email', 'email'),
array('email', 'unique'),
...
);
}
Try this:
As per your given code, It seems ok
You can verify using this url about validation:
http://www.yiiframework.com/doc/guide/1.1/en/form.model#declaring-validation-rules