I'm using Kohana 3.3 in my project and I'm trying to get the User Registration and Login working. I am using ORM's Auth and Kostache for managing my layout/templates.
How do I:
- Check if Username already exists? If it does return to error_msg.mustache a message "User already Exists"
- Check if username and email is valid according to my model rules? If not return error message to error_msg.mustache indicating what validation failed
In my controller I have:
class Controller_User extends Controller {
public function action_signup()
{
$renderer = Kostache_Layout::factory();
$this->response->body($renderer->render(new View_FrontEnd_User, 'frontend/signup'));
}
public function action_createuser()
{
try {
$user = ORM::factory('User');
$user->username = $this->request->post('username');
$user->password = $this->request->post('password');
$user->email = $this->request->post('email');
// How do I:
// Check if Username already exists? If it does return to error_msg.mustache a message "User already Exists"
// Check if email is valid? If not return error message to error_msg.mustache indicating "email is not valid"
$user->save();
}
catch (ORM_Validation_Exception $e)
{
$errors = $e->errors();
}
}
}
In my Model:
<?php
class Model_User extends Model_Auth_User
{
public function rules()
{
return array(
'username' => array(
array('not_empty'),
array('min_length', array(':value', 4)),
array('max_length', array(':value', 32)),
array('regex', array(':value', '/^[-\pL\pN_.]++$/uD')),
),
'email' => array(
array('not_empty'),
array('min_length', array(':value', 4)),
array('max_length', array(':value', 127)),
array('email'),
),
);
}
}
Thanks a lot in advance!
You can do the uniqueness check using Validation and an already-written callback. This has the advantages of keeping your validation logic together, and of being very concise:
As simple as that!
I originally answered this question with my own solution, which is slightly different from the pre-rolled version, but now that I know about that obviously I'll use it instead of this: