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
Related
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'),
);
}
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
What i'm doing wrong?
<?php
public function login() {
$user_name = time();
User::create(array(
'name' => $user_name,
'email' => $user_name.'#test.com',
'password' => Hash::make('123123'),
));
$user = array(
'email' => $user_name.'#test.com',
'password' => '123123',
);
$m = User::where('email' , '=', $user_name.'#test.com')->first();
dd([
'Auth::attempt($user)',
Auth::attempt($user),
'Auth::check()',
Auth::check(),
'Hash::check($m->password, \'123123\')',
Hash::check($m->password, '123123')
]);
}
Result:
array(6) {
[0]=>
string(20) "Auth::attempt($user)"
[1]=>
bool(false)
[2]=>
string(13) "Auth::check()"
[3]=>
bool(false)
[4]=>
string(38) "Hash::check($user->password, '123123')"
[5]=>
bool(false)
}
Not sure what information should I add.
app/config/auth.php
'driver' => 'eloquent',
'model' => 'User',
'table' => 'users',
app/config/app.php
'key' => 'DMmiPAxSYz4O2jG44S92OcdPZN7ZsGGs',
'cipher' => MCRYPT_RIJNDAEL_256,
models/User.php
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* Validation rules
*/
public static $rules = array(
'name' => 'required',
'email' => 'email|required|unique',
'password' => 'min:6',
);
/**
* Validation rules
*/
public static $messages = array(
'name.required' => 'The name field is required',
'email.email' => 'The email field must contain properly formatted email.',
'email.required' => 'The email field is required',
'password.required' => 'The password field is required',
'password.min:6' => 'The password must be minimum 6 characters long',
);
protected $table = 'users';
protected $hidden = array('password', 'remember_token');
protected $guarded = array('id');
public function setPasswordAttribute($value) {
if ($value) {
$this->attributes['password'] = Hash::make($value);
}
}
}
Well here's some checks that you can do
Have you setup config/auth.php with driver, model and table?
Have you filled the fillable array of the User's model?
Have you change the key inside config/app.php ?
Also try to dd($m) in order to see what you got from that query.
I found what is wrong.
This part of code hash password for first time:
User::create(array(
'name' => $user_name,
'email' => $user_name.'#test.com',
'password' => Hash::make('123123'), // <---- first time
));
And this mutator in User model does hashing for second time before put password to database:
public function setPasswordAttribute($value) {
if ($value) {
$this->attributes['password'] = Hash::make($value); // <---- second time
}
}
So I just changed first block to this:
User::create(array(
'name' => $user_name,
'email' => $user_name.'#test.com',
'password' => '123123', // <---- no hashing here
));
I am using CakePHP 2.3, I want to save data as follows follows:
$insertUser = array(
'Name' => $Name,
'LastName' => $lastName,
'password' => $password,
'email' => $email,
'TimeStamp' => $presentTime,
'RefererUserId' => $refererId // set the referer user id
);
$this->SystemUser->saveAll($insertUser) // save record in table.
The above code is not working. I tried another method like:
$this->SystemUser->query("INSERT INTO system_users(Name,LastName,password,email,TimeStamp,RefererUserId) VALUES ('{$Name}','{$lastName}','{$password}','{$email}','{$presentTime}','{$refererId}')");
How can I now get the last inserted id? I used getLastInsertId() to get last inserted id, as below:
$lastid = $this->SystemUser->getLastInsertId();
But it does not seem to work.
Please try the below code. SystemUser is assumed as your model name.
$this->user_data = array(
'SystemUser' => array(
'Name' => $Name,
'LastName' => $lastName,
'password' => $password,
'email' => $email,
'TimeStamp' => $presentTime,
'RefererUserId' => $refererId // set the referer user id
));
if ($this->SystemUser->save($this->user_data)) {
$lastid = $this->SystemUser->getLastInsertId();
} else {
// do something
}
Your $insertUser should be the following
$insertUser['SystemUser'] = array(
'Name' => $Name,
'LastName' => $lastName,
'password' => $password,
'email' => $email,
'TimeStamp' => $presentTime,
'RefererUserId' => $refererId // set the referer user id
);
Then you should be save data as like
if($this->SystemUser->save($insertUser)) {
$lastid = $this->SystemUser->getLastInsertId();
} else {
debug($this->SystemUser->validationErrors); die();
}
This will probably give you the info you need (assuming it's not saving because of invalid data, of course):
debug($this->SystemUser->validationErrors); die();
That's it.
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'),
);
}