What is the Validation in Model

Obullo has a Vmodel model class who want to do validation in model instead of controller. Validation model class use Validator Class to form validations. Using Validation Model you can create Native or Ajax forms easily.

If you want to use Vmodel Class simply extend your model to it.

<?php Class User extends Vmodel
{
    function __construct()
    {
        parent::__construct();
    }
    
    public $settings = array(
    'database' => 'db',
    'table'    => 'users',
    'primary_key' => 'usr_id',
    'fields' => array
     (
        'usr_id' => array(
          'label' => 'ID',
          'type'  => 'int',
          'rules' => 'trim|integer'
        ),
        'usr_username' => array(
         'label'  => 'Username',  // you can use lang:username
         'type'   => 'string',
         'rules'  => 'required|trim|unique|min_lenght[3]|max_length[100]|xss_clean'
        ),
        'usr_password' => array(
          'label' => 'Password',
          'type'  => 'string',
          'rules' => 'required|trim|min_lenght[6]|encrypt',
          'func'  => 'md5'
        ),
        'usr_confirm_password' => array(
          'label' => 'Confirm Password',
          'type'  => 'string',
          'rules' => 'required|encrypt|matches[usr_password]'
        ),
        'usr_email' => array(
          'label' => 'Email Address',
          'type'  => 'string',
          'rules' => 'required|trim|valid_email'
        )
    ));
}

As you can see above the example we just put validation rules public $settings variable then we save the class in /models directory.

Load the User Model from your controller and see the action

loader::model('user', FALSE);  // Include user model
        
$user = new User();
$user->usr_username = 'blabla';    // Set string or a post/get variable
$user->usr_password = i_get_post('usr_password');
$user->usr_email    = i_get_post('usr_email');

if($user->save())
{
     echo 'Saved !'

else
{
     print_r($user->errors());
}

Validation Model Tutorial

Download the Obullo Framework and you will find the a real Validation Model Tutorial in the modules/test/vm folder then just run this url.

http://localhost/framework/index.php/test/vm/start

Function Reference

$model->errors($field = '');

This function return to all errors in array format if you don't provide any fieldname, otherwise it will return to one field error.

print_r($model->errors());

Array
(
    [usr_username] => The Username field is required.
    [usr_password] => The Password field is required.
    [usr_confirm_password] => The Confirm Password field is required.
    [usr_email] => The Email Address field is required.
    [success] => 0
)

If save function run successfully then the [success] array value will be 1 (true) otherwise it will return to 0 (false).

$model->set_error($field = '', $message = '');

You can set custom errors.

$model->set_field($field = '', $type = 'rules', $val = ' new value ');

Using set field function you can set validation settings or rules dynamically.

loader::model('model_user', FALSE);
            
 $model = new Model_User();
            
// override to rule of  usr_username.
$model->set_field('usr_username', 'rules', 'trim|required');

$model->where('usr_username',  'someusername');
            
if($model->delete())
{               
     echo form_send_success();

     return;
}

$model->values($field = '');

Function return to filtered secure value after that the validation according to your variable type of your validation rules in your model $settings .

print_r($model->values());

Array
(
    [usr_id] => 0
    [usr_username] => 'blabla'
    [usr_password] => 
    [usr_confirm_password] => 
    [usr_email] => 
)

$model->save();

Function will save the all variables to database which are the fields matches in your model class $settings => fields section.

$user->usr_username = 'blabla';    // Set string or a post/get variable
$user->usr_password = i_get_post('usr_password');
$user->save();

Function will return to TRUE if success, otherwise it will return to FALSE.

$model->delete();

Function will delete the all variables to database which are the fields matches in your model class $settings => fields section.

$user->usr_username = 'blabla';    // Set string or a post/get variable
$user->usr_password = i_get_post('usr_password');
$user->delete();

Delete providing by fieldname

loader::model('user', FALSE);  // Include user model

$user = new User();

$user->where('usr_id', 5);

if($user->delete())
{
    echo 'User Deleted Successfuly !';
}

print_r($user->errors());

Delete providing by array

loader::model('user', FALSE);  // Include user model

$user = new User();

$user->where_in('usr_id', array('1', '4', '5'))

if($user->delete())
{
    echo 'User Deleted Successfuly !';
}

print_r($user->errors());

You can define your Custom Save or Custom Delete function in your model class, just remove the parent::save(); method and put your own functions.

function save()
{   
    $result = parent::save();

    return $result;
}

Functions will return to TRUE if success, otherwise they will return to FALSE.

$model->validation();

Function will return FALSE if $model validation success.

$model->validate($fields = array());

If you don't want to save fields to database, just want to validation you can use the validation requests function, if you provide any array data fields, function validate just them, otherwise function validate the all fields.

loader::model('member', FALSE);
$member  = new Member();

$member_form  = $member->validate(array('usr_agreement'));

if($member_form)
{
     Everythings ok !
}

$model->no_save($field);

Some times we don't want to save some fields or that the fields which we haven't got in the db tables we have to validate them.Overcome to this problem we use $model->no_save(); function.

loader::model('member', FALSE);

$member  = new Member();

$model->usr_first_lastname   = i_get_post('usr_first_lastname');
$model->usr_password         = i_get_post('usr_password');

$member->no_save('usr_agreement'); // we don't have these fields in the db table.
$member->no_save('usr_password_confirm');

if($member->save())
{
    echo 'Saved New Nember !';
}

$model->item($var);

Fetch items from your model $settings variable.

echo $model->item('primary_key');
echo $model->item('fields['usr_id']');

$model->debug();

You can grab the latest SQL query.

$model->debug();

parent::validate($fields);

Using a parent validate function you can validate the items when you work inside the model.

Class User extends Vmodel
{
    function __construct()
    {
        parent::__construct();
    }
    
    public $settings = array(
    'database' => 'db',
    'table'    => 'users',
    'primary_key' => 'usr_id',
    'fields' => array
     (
        'usr_id' => array(
          'label' => 'ID',
          'type'  => 'int',
          'rules' => 'trim|integer'
        )
    ));
    
    function get($limit = '', $offset = '', $id = '')
    {        
        $this->db->select('*');
        
        if($id != '')
        {
            $data = array('id' => $id);
            parent::validate($data);  // manually validate ID field
        }
        
        return $this->db->get('users', $limit, $offset);
    }
}

$this->before_save();

Creating a before save function in your model, you can control the saving extra jobs before the saving data to current table. Forexample you can keep the user logs into database using it.

function before_save()
{
    $data['usr_ip'] = i_ip_address();

    $this->db->insert('usr_logs', $data);
}

$this->after_save();

Creating a after save function in your model, you can control the saving extra jobs after the saving data to current table. Forexample you can keep the saved data as log into database using it.

function after_save()

    $array = array();
    foreach($this->settings['fields'] as $key => $val)
    {
          $array[$key]  = $this->values($key);
    }

    $data['saved_data'] = seralize($array);

    $this->db->insert('save_logs', $data);
}

Rule Reference

The following is a list of all the native rules that are available to use:

Rule Parameter Description Example
required No Returns FALSE if the form element is empty.
matches Yes Returns FALSE if the form element does not match the one in the parameter. matches[form_item]
min_length Yes Returns FALSE if the form element is shorter then the parameter value. min_length[6]
max_length Yes Returns FALSE if the form element is longer then the parameter value. max_length[12]
exact_length Yes Returns FALSE if the form element is not exactly the parameter value. exact_length[8]
alpha No Returns FALSE if the form element contains anything other than alphabetical characters.
alpha_numeric No Returns FALSE if the form element contains anything other than alpha-numeric characters.
alpha_dash No Returns FALSE if the form element contains anything other than alpha-numeric characters, underscores or dashes.
numeric No Returns FALSE if the form element contains anything other than numeric characters.
integer No Returns FALSE if the form element contains anything other than an integer.
is_natural No Returns FALSE if the form element contains anything other than a natural number: 0, 1, 2, 3, etc.
is_natural_no_zero No Returns FALSE if the form element contains anything other than a natural number, but not zero: 1, 2, 3, etc.
valid_email No Returns FALSE if the form element does not contain a valid email address.
valid_email_dns No Returns FALSE if the form element does not contain a valid email AND dns query return to FALSE.
valid_emails Yes Returns FALSE if any value provided in a comma separated list is not a valid email. (If parameter TRUE or 1 function also will do a dns query foreach emails) valid_emails[true]
valid_ip No Returns FALSE if the supplied IP is not valid.
valid_base64 No Returns FALSE if the supplied string contains anything other than valid Base64 characters.
no_space No Returns FALSE if the supplied string contains space characters.
callback_function[param] Yes You can define a custom callback function which is a class method located in your current model or just a function. callback_functionname[param]
callback_request[method][request_uri] Yes Returns TRUE if the supplied hmvc request response == 1 or response == 'TRUE' otherwise returns FALSE . calback_request[post][/captcha/check/]
valid_date Yes Returns FALSE if the supplied date is not valid in current format. Enter your date format default is mm-dd-yyyy.

Prepping Reference

The following is a list of all the prepping functions that are available to use:

Name Parameter Description
xss_clean No Runs the data through the XSS filtering function, described in the Security Helper page.
prep_for_form No Converts special characters so that HTML data can be shown in a form field without breaking it.
prep_url No Adds "http://" to URLs if missing.
strip_image_tags No Strips the HTML from image tags leaving the raw URL.
encode_php_tags No Converts PHP tags to entities.

Ajax Form Plugin Rules

If you use ajax requests you need to Form Send Helper to encode Validaton Model Response in Json format. If you use Obullo Jquery Form Plugin the following is a list of all the Form plugin functions that are available to use

you can control the form plugin functions using the class attribute

<? echo form_open('/test/vm/start/do_post.json', array('method' => 'POST', 'class' => 'hide-form no-top-msg'));?>

Ajax Form Plugin Attributes

Attribute Description
no-top-msg Form plugin default show a top message warn to user that you can disable this functionality using as class attribute in your form.
no-ajax If you disable to ajax post you can use no-ajax class attribute, when the user click to submit button form will do a native post request instead of ajax post.
hide-form If the form successfully posted with no errors you can hide the form area and you can show the users just success message.

Using AJAX - Vmodel and Form Send Helper

After that load the Obullo JQuery Form Plugin just create a do_post() function in your controller then you need add a form_open('module/controller/do_post.json'); code in your view file, remember we have a ajax form tutorial in modules/test folder. You can look at there for more details.

function do_post() 
{
    loader::model('user', FALSE);  // Include user model
    loader::helper('ob/form_send');

    $user = new User();
    $user->usr_username = i_get_post('usr_username');
    $user->usr_password = i_get_post('usr_password');
    $user->usr_email    = i_get_post('usr_email');

    if($user->save())
    {
            echo form_send_success($model);
            return;
    } 
    else
    {
            echo form_send_error($user);
            return;
    }
}

Sending Custom Messages

function do_post() 
{
    loader::model('user', FALSE);  // Include user model
    loader::helper('ob/form_send');

    $user = new User();
    $user->usr_username = i_get_post('usr_username');
    $user->usr_password = i_get_post('usr_password');
    $user->usr_email    = i_get_post('usr_email');

    if($user->save())
    {
            $user->set_error('msg', 'Data Saved Successfully !');

            echo form_send_success($user);
            return;
    } 
    else
    {
            echo form_send_error($user);
            return;
    }
}

Transaction Support

Vmodel Library automatically support the transactions if your table engine setted correctly as INNODB. If you want to learn more details about transactions look at database transactions section.