Hello Guys! It's time to start another tutorial. This time I thought to do a practical and real world example as  a web application. It's a Registration form! Now you will get bored. If so, you are going miss the opportunity. This is not a simple form guys! It has a lot of functionalities including validations done real time...When you register to a site you may already have seen these functionalities.But today I'm going to show you how to implement them!!! These are functions this form has...
  • Check username availability 
  • Check username length 
  • Check email type 
  • Check phone number length 
  • Check image format 
  • Image upload and preview Image remove 
  • Check password length 
  • Check password strength 
  • Check confirm password matching 
Impressive? We can go ahead step by step.. First I need to tell you the technologies that I will use today.
  • Codeigniter as PHP framework
  • Bootstrap as CSS framework
  • Ajax and jQuery
  • jQuery and CSS plugins Validation plugin and Dropify plugin
Download Links:
  1. Click here Download Dropify and here you have a simple documentation on it.            Special thanks goes to Jeremy FAGIS for this amazing plugin!
  2. Click here to download jQuery validation plugin.
  3. Codeigniter
  4. Bootstrap
Download Source CodeRegistration Form

Since I'm a guy works with Codeigniter, here you have to setup your project with CI.

Before I start, I'll show you a short demo video about today's tutorial...


First download Codeigniter and create a project folder in your localhost(htdocs or www folder). In my case its name is CIAjaxRegForm. Then move the Codeigniter files into the project folder. Go to phpMyadmin and create a new database called db_reg. Then cretaew a new table called users
SQL code to create the Table:
CREATE TABLE `users` ( `user_id` int(5) NOT NULL,
`username` varchar(10) NOT NULL,
`fullname` varchar(100) NOT NULL,
`email` varchar(50) NOT NULL,
`phone` varchar(10) NOT NULL,
`image` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL ) ;

Next you have to do adjust configurations for CI project.

Project folder =>  CIAjaxRegForm
Base URL => $config['base_url'] = 'http://localhost/CIAjaxRegForm/
Database name => db_reg
Database table name => users
Autoload libraries => database
Autoload helpers => form , url, file
Default Controller => Register

Important : 
file helper must be loaded. Otherwise images can not be uploaded!

As a start, create these 3 files! That's it. Then we can go for the code.
In my project folder, I use these files.
register.php          -  to load the view the registration form and scripts
Register.php         -  controller to implement the actions
User_model.php   -  to insert and check data with database

Create Register controller to load the view.

Register.php


<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Register extends CI_Controller {
 public function __construct()
 {
  parent::__construct();
  $this->load->model('User_model');
 }

 public function index()
 {
  $this->load->view('register');
 }
}

Now I will create register.php to view the form.
Note: This is the view without scripts. Later I will add them.

register.php   -   version 1


<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>Registration Form</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="<?php echo base_url() ?>assets/css/bootstrap.css">
    <!-- dropify CSS -->
    <link rel="stylesheet" href="<?php echo base_url() ?>assets/dropify/css/dropify.css">
    <!-- Font Awesome CSS -->
    <link rel="stylesheet" href="<?php echo base_url() ?>assets/font-awesome/css/font-awesome.min.css">
    <!-- set color for jQuery error messages -->
    <style type="text/css">
        /*CSS for validation plugin error*/
        .error {
            color: #C6070A;
        }
        /*CSS for password strength checker messages*/
        .short{
            color:#FF0000;
        }
        .weak{
            color:orange;
        }
        .good{
            color:blue;
        }
        .strong{
            color: green;
        }
    </style>
</head>
<body>
   <div class="col-lg-12">
    <h3 style="margin-top: 30px;text-align: center;">Registration Form with Real Time Validations using <span class="text-primary">jQuery validation plugin</span>, <span class="text-success">Dropify plugin</span>, <span class="text-warning">CI</span> and <span class="text-danger">Ajax</span></h3>
        <div class="row">
            <div class="col-lg-4">
                <div class="card" style="margin-top: 25px;">
                    <br>
                    <div class="card-body">
                        <p style="text-align: justify;">I have designed this registration form including the below functionalities. All are done real time...</p>
                        <ul class="list-group">
                          <li class="list-group-item"><span class="col-lg-1"><i class="fa fa-user-circle-o" aria-hidden="true"></i></span> Check username availability</li>
                          <li class="list-group-item"><span class="col-lg-1"><i class="fa fa-user-circle" aria-hidden="true"></i></span> Check username length</li>
                          <li class="list-group-item"><span class="col-lg-1"><i class="fa fa-envelope-open" aria-hidden="true"></i></span> Check email type</li>
                          <li class="list-group-item"><span class="col-lg-1"><i class="fa fa-phone" aria-hidden="true"></i></span> Check phone number length</li>
                          <li class="list-group-item"><span class="col-lg-1"><i class="fa fa-file-text-o" aria-hidden="true"></i></span> Check image format</li>
                          <li class="list-group-item"><span class="col-lg-1"><i class="fa fa-eye" aria-hidden="true"></i></span> Image upload and preview</li>
                          <li class="list-group-item"><span class="col-lg-1"><i class="fa fa-minus-circle" aria-hidden="true"></i></span> Image remove</li>
                          <li class="list-group-item"><span class="col-lg-1"><i class="fa fa-key" aria-hidden="true"></i></span> Check password length</li>
                          <li class="list-group-item"><span class="col-lg-1"><i class="fa fa-check-circle-o" aria-hidden="true"></i></span> Check password strength</li>
                          <li class="list-group-item"><span class="col-lg-1"><i class="fa fa-key" aria-hidden="true"></i></span> Check confirm password matching</li>
                        </ul>
                    </div>
                </div>           
            </div>
            <div class="col-lg-8">
                <br>              
                <div class="card" style="margin-bottom: 50px;">
                    <br>
                    <div class="card-body">
                        <!-- success message to be displayed after adding a user to the database successfully -->
                        <?php if($this->session->flashdata('success')): ?>
                            <div class="alert alert-success alert-dismissible" role="alert">
                                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                                    <?php echo $this->session->flashdata('success');?>
                            </div>
                        <?php endif; ?>
                        <!-- Form -->
                        <?php echo form_open_multipart('Register/signUp', array('id' => 'register-form','method' => 'POST'));?>
                            <div class="form-row">
                             <div class="col">
                                 <label>Username</label>  
                                 <br>                        
                                    <input type="text" id="username" name="username" class="form-control" placeholder="Enter a Username">
                                    <div id="username_result"></div>
                                   
                                </div> 
                             <div class="col">
                                <label>Full Name</label>
                                <br>
                                    <input type="text" id="fullname" name="fullname" class="form-control" placeholder="Enter Your Full Name">
                                <br>
                             </div>                                                                        
                            </div>                          
                            <div class="form-row">
                             <div class="col">
                                <label>Email</label>
                                <br>
                                    <input type="email" id="email" name="email" class="form-control" placeholder="Enter Your Email">
                                <br>
                             </div>
                             <div class="col">
                                <label>Phone Number</label>
                                <br>
                                    <input type="text" id="phone" name="phone" class="form-control" placeholder="Enter Mobile number">
                                <br>
                             </div>
                            </div>                                            
                            <div class="form-row">
                                <div class="col">
                                <label>Password</label>
                                <br>
                                    <input type="password" id="password" name="password" class="form-control" placeholder="Type a Password">
                                    <div id="result"></div>
                                <br>
                                </div>
                             <div class="col">
                                <label>Confirm Password</label>
                                <br>
                                    <input type="password" id="cpassword" name="cpassword" class="form-control" placeholder="Retype Your Password">
                                <br>  
                                </div>
                            </div>  
                            <div class="form-row">
                              <div class="col">
                                <label>Profile Picture</label>
                                <br>
                                    <!-- include class dropify and check extension -->
                                    <input type="file" id="userfile" name="userfile" class="dropify" data-allowed-file-extensions="jpg png gif jpeg">
                                <br>
                                </div>
                                <div class="col"></div>                          
                            </div>                                                                          
                            <input type="submit" class="btn btn-primary" value="Register">
                            <br><br>                                     
                        <?php echo form_close();?>              
                    </div>
                </div>
            </div> 
        </div>    
    </div>
    <!-- jQuery JS -->
    <script src="<?php echo base_url() ?>assets/js/jquery-3.2.1.min.js"></script>
    <!-- dropify JS -->
    <script src="<?php echo base_url() ?>assets/dropify/js/dropify.js"></script>
    <!-- jQuery validation plugin JS -->
    <script src="<?php echo base_url() ?>assets/js/jquery.validate.js"></script>
    <!-- Bootstrap JS -->
    <script src="<?php echo base_url() ?>assets/js/bootstrap.js"></script> 
</body>
</html>

Now you have the front end view. So we can use the jQuery validation plugin and dropify plugin for input fields. Add the below code before the ending body tag.

    <script type="text/javascript">
        // wait untill the page is loaded completely
        $(document).ready(function(){
            // include the dropify function comes with dropify JS
         $('.dropify').dropify();
            // include the validation plugin for the form
            $('#register-form').validate({
            // set validation rules for input fields
                rules: {
                    username: {
                        required : true
                    },
                    fullname: {
                        required : true
                    },                   
                    email: {
                        required : true,
                        email: true
                    },
                    phone: {
                        required : true,
                        minlength: 10
                    },                    
                    password: {
                        required : true                        
                    },
                    cpassword: {
                        required : true,
                        equalTo: "#password"
                    }
                },
            // set validation messages for the rules are set previously
                messages: {
                    username: {
                        required : "Username is required"
                        
                    },
                    fullname: {
                        required : "Full Name is required"
                    },                    
                    email: {
                        required : "Email is required",
                        email: "Enter a valid email. Ex: example@gmail.com"
                    },
                    phone: {
                        required : "Phone Number is required",
                        minlength: "Password must contain 10 numbers"
                    },                   
                    password: {
                        required : "Password is required"
                    },
                    cpassword: {
                        required : "Confirm Password is required",
                        equalTo: "Confirm Password must be matched with Password"
                    }                   
                }
            });
        });
    </script> 

Explanation:
<input type="file" id="userfile" name="userfile" class="dropify" data-allowed-file-extensions="jpg png gif jpeg">
Here I have included a class called dropify. That's the class that enables the new style for input file button. Then another attribute has been introduced. It means the allowed extension formats. It you select a format not included here, it will show errors.

 $('.dropify').dropify();
To include the dropify JS actions, you have to put this code after jQuery document ready function is started!

Then the validation plugin configuration are done. I have already published an article on it. If you have missed it, visit here to get the idea.

If you followed me, when you click on register button, error messages will be shown for input fields saying they are required..

Username Availability

Now we have to implement the function to check username availability. An ajax request is sent to the server an the entered username is checked real time. It needs a jQuery+Ajax function, CI controller function and a CI model function. For now I will put the code for jQuery+Ajax function.

register view script  -  jQuery change function

            // check the username availability real time
            $('#username').change(function(){
                var username = $('#username').val();
                if(username != ''){
                    $.ajax({
                        url: "<?php echo base_url(); ?>Register/checkUsername",
                        method: "POST",
                        data: {username:username},
                        success: function(data){
                            $('#username_result').html(data);
                        }
                    });
                }
            });

Controller is Register and the function is checkUsername. Now we have to implement the controller function to do this. Add the below function to the controller.

Register controller  -  checkUsername function

 {
  // check the username is already used one or not
  if($this->User_model->getUsername($_POST['username'])){
   echo '<label class="text-danger"><span><i class="fa fa-times" aria-hidden="true">
   </i> This user is already registered</span></label>';
  }
  else {
   // check the username length is greater than 5 or equal to 5
   if (strlen($_POST['username'])>=5) {
    echo '<label class="text-success"><span><i class="fa fa-check-circle-o" aria-hidden="true"></i> Username is available</span></label>';
   }
   else {
    echo '<label class="text-danger"><span><i class="fa fa-times" aria-hidden="true"></i> Username must contain at least 5 characters</span></label>';
   }   
  }
 }

For this function, we need a model function to check username in database! This is it..

User_model  -  getUsername function

 // get username from database
 public function getUsername($username)
 { 
  // find the username matched with the input
  $this->db->where('username' , $username);
  $query = $this->db->get('users');
  // check whether there are matching records
  if($query->num_rows()>0){
   return true;
  }
  else {
   return false;
  }
 }


Password Strength

Final validation part is checking the password strength..This is the jQuery function for it.

register view script  -  jQuery checkStrength function

            $('#password').keyup(function() {
                $('#result').html(checkStrength($('#password').val()))
                })
                function checkStrength(password) {
                var strength = 0
                if (password.length < 6) {
                    $('#result').removeClass()
                    $('#result').addClass('short')
                    return '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Too short'
                }
                if (password.length > 7) strength += 1
                // If password contains both lower and uppercase characters, increase strength value.
                if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) strength += 1
                // If it has numbers and characters, increase strength value.
                if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) strength += 1
                // If it has one special character, increase strength value.
                if (password.match(/([!,%,&,@,#,$,^,*,?,_,~])/)) strength += 1
                // If it has two special characters, increase strength value.
                if (password.match(/(.*[!,%,&,@,#,$,^,*,?,_,~].*[!,%,&,@,#,$,^,*,?,_,~])/)) strength += 1
                // Calculated strength value, we can return messages
                // If value is less than 2
                if (strength < 2) {
                    $('#result').removeClass()
                    $('#result').addClass('weak')
                    return '<i class="fa fa-exclamation-circle" aria-hidden="true"></i> Weak'
                } else if (strength == 2) {
                    $('#result').removeClass()
                    $('#result').addClass('good')
                    return '<i class="fa fa-check" aria-hidden="true"></i> Good'
                } else {
                    $('#result').removeClass()
                    $('#result').addClass('strong')
                    return '<i class="fa fa-thumbs-up" aria-hidden="true"></i> Strong'
                }
            }

OK..Now you ready for all front end validation. The below screenshot is one of the situations captured.
After all these validations, data should be inserted to the database. So we need another CI controller function and a CI model function. Now I'm going to create them.

Register controller  -  signUp function

 public function signUp()
 {
  $config['upload_path'] = './assets/images';   // uploading folder
  $config['allowed_types'] = 'gif|jpg|png|jpeg';
  $config['max_size'] = '2048000';   // max size in KB
  $config['max_width'] = '20000';    //  max resolution width
  $config['max_height'] = '20000';   //max resolution height
  // load CI libarary called upload 
  $this->load->library('upload', $config);
  // body of if clause will be executed when image uploading is failed
  if(!$this->upload->do_upload()){
   $errors = array('error' => $this->upload->display_errors());
   // This image is uploaded by default if the selected image is not uploaded
   $image = 'no_image.png';    
  }
  // body of else clause will be executed when image uploading is succeeded
  else{
   $data = array('upload_data' => $this->upload->data());
   $image = $_FILES['userfile']['name'];  //name must be userfile  
  }
        $this->User_model->insertUser($image);
        //set message to be shown when registration is completed
        $this->session->set_flashdata('success','<span><i class="fa fa-check-circle-o" aria-hidden="true">
   </i> User is registered!</span>');
        redirect('Register');  
 }

User_model  -  insertUser function

 // store a user
 public function insertUser($image)
 {
        $data = array(
         //assign user data into array elements
         'user_id' => $this->input->post('user_id'),
         'username' => $this->input->post('username'),
         'fullname' => $this->input->post('fullname'),
         'email' =>$this->input->post('email'),
         'phone' =>$this->input->post('phone'),
         'password' =>sha1($this->input->post('password')),
         'image' => $image
     );
  // insert data to the database
  $this->db->insert('users', $data);
 }

Long tutorial? It may be due to the content and topics I covered!

Conclusion:

Finally I can give you the full code for 3 files to avoid your confusions...

Final view  -  register.php


<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>Registration Form</title>
    <!-- Bootstrap CSS -->
 <link rel="stylesheet" href="<?php echo base_url() ?>assets/css/bootstrap.css">
    <!-- dropify CSS -->
 <link rel="stylesheet" href="<?php echo base_url() ?>assets/dropify/css/dropify.css">
    <!-- Font Awesome CSS -->
    <link rel="stylesheet" href="<?php echo base_url() ?>assets/font-awesome/css/font-awesome.min.css">
    <!-- set color for jQuery error messages -->
 <style type="text/css">
        /*CSS for validation plugin error*/
  .error {
   color: #C6070A;
  }
        /*CSS for password strength checker messages*/
        .short{
            color:#FF0000;
        }
        .weak{
            color:orange;
        }
        .good{
            color:blue;
        }
        .strong{
            color: green;
        }
 </style>
</head>
<body>
   <div class="col-lg-12">
    <h3 style="margin-top: 30px;text-align: center;">Registration Form with Real Time Validations using <span class="text-primary">jQuery validation plugin</span>, <span class="text-success">Dropify plugin</span>, <span class="text-warning">CI</span> and <span class="text-danger">Ajax</span></h3>
        <div class="row">
            <div class="col-lg-4">
                <div class="card" style="margin-top: 25px;">
                    <br>
                    <div class="card-body">
                        <p style="text-align: justify;">I have designed this registration form including the below functionalities. All are done real time...</p>
                        <ul class="list-group">
                          <li class="list-group-item"><span class="col-lg-1"><i class="fa fa-user-circle-o" aria-hidden="true"></i></span> Check username availability</li>
                          <li class="list-group-item"><span class="col-lg-1"><i class="fa fa-user-circle" aria-hidden="true"></i></span> Check username length</li>
                          <li class="list-group-item"><span class="col-lg-1"><i class="fa fa-envelope-open" aria-hidden="true"></i></span> Check email type</li>
                          <li class="list-group-item"><span class="col-lg-1"><i class="fa fa-phone" aria-hidden="true"></i></span> Check phone number length</li>
                          <li class="list-group-item"><span class="col-lg-1"><i class="fa fa-file-text-o" aria-hidden="true"></i></span> Check image format</li>
                          <li class="list-group-item"><span class="col-lg-1"><i class="fa fa-eye" aria-hidden="true"></i></span> Image upload and preview</li>
                          <li class="list-group-item"><span class="col-lg-1"><i class="fa fa-minus-circle" aria-hidden="true"></i></span> Image remove</li>
                          <li class="list-group-item"><span class="col-lg-1"><i class="fa fa-key" aria-hidden="true"></i></span> Check password length</li>
                          <li class="list-group-item"><span class="col-lg-1"><i class="fa fa-check-circle-o" aria-hidden="true"></i></span> Check password strength</li>
                          <li class="list-group-item"><span class="col-lg-1"><i class="fa fa-key" aria-hidden="true"></i></span> Check confirm password matching</li>
                        </ul>
                    </div>
                </div>           
            </div>
            <div class="col-lg-8">
                <br>              
                <div class="card" style="margin-bottom: 50px;">
                    <br>
                    <div class="card-body">
                        <!-- success message to be displayed after adding a user to the database successfully -->
                        <?php if($this->session->flashdata('success')): ?>
                            <div class="alert alert-success alert-dismissible" role="alert">
                                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                                    <?php echo $this->session->flashdata('success');?>
                            </div>
                        <?php endif; ?>
                        <!-- Form -->
                        <?php echo form_open_multipart('Register/signUp', array('id' => 'register-form','method' => 'POST'));?>
                            <div class="form-row">
                             <div class="col">
                                 <label>Username</label>  
                                 <br>                        
                                    <input type="text" id="username" name="username" class="form-control" placeholder="Enter a Username">
                                    <div id="username_result"></div>
                                   
                                </div> 
                             <div class="col">
                                <label>Full Name</label>
                                <br>
                                    <input type="text" id="fullname" name="fullname" class="form-control" placeholder="Enter Your Full Name">
                                <br>
                             </div>                                                                        
                            </div>                          
                            <div class="form-row">
                             <div class="col">
                                <label>Email</label>
                                <br>
                                    <input type="email" id="email" name="email" class="form-control" placeholder="Enter Your Email">
                                <br>
                             </div>
                             <div class="col">
                                <label>Phone Number</label>
                                <br>
                                    <input type="text" id="phone" name="phone" class="form-control" placeholder="Enter Mobile number">
                                <br>
                             </div>
                            </div>                                            
                            <div class="form-row">
                                <div class="col">
                                <label>Password</label>
                                <br>
                                    <input type="password" id="password" name="password" class="form-control" placeholder="Type a Password">
                                    <div id="result"></div>
                                <br>
                                </div>
                             <div class="col">
                                <label>Confirm Password</label>
                                <br>
                                    <input type="password" id="cpassword" name="cpassword" class="form-control" placeholder="Retype Your Password">
                                <br>  
                                </div>
                            </div>  
                            <div class="form-row">
           <div class="col">
                                <label>Profile Picture</label>
                                <br>
                                    <!-- include class dropify and check extension -->
                                    <input type="file" id="userfile" name="userfile" class="dropify" data-allowed-file-extensions="jpg png gif jpeg">
                                <br>
                                </div>
                                <div class="col"></div>                          
                            </div>                                                                          
                            <input type="submit" class="btn btn-primary" value="Register">
                            <br><br>                                     
                        <?php echo form_close();?>              
                    </div>
                </div>
            </div> 
        </div>    
    </div>
    <!-- jQuery JS -->
    <script src="<?php echo base_url() ?>assets/js/jquery-3.2.1.min.js"></script>
    <!-- dropify JS -->
    <script src="<?php echo base_url() ?>assets/dropify/js/dropify.js"></script>
    <!-- jQuery validation plugin JS -->
 <script src="<?php echo base_url() ?>assets/js/jquery.validate.js"></script>
    <!-- Bootstrap JS -->
 <script src="<?php echo base_url() ?>assets/js/bootstrap.js"></script>
    <!-- validation plugin configuration -->
    <script type="text/javascript">
        // wait untill the page is loaded completely
        $(document).ready(function(){
            // include the dropify function comes with dropify JS
         $('.dropify').dropify();
            // check the username availability real time
            $('#username').change(function(){
                var username = $('#username').val();
                if(username != ''){
                    $.ajax({
                        url: "<?php echo base_url(); ?>Register/checkUsername",
                        method: "POST",
                        data: {username:username},
                        success: function(data){
                            $('#username_result').html(data);
                        }
                    });
                }
            });
            // include the validation plugin for the form
            $('#register-form').validate({
            // set validation rules for input fields
                rules: {
                    username: {
                        required : true
                    },
                    fullname: {
                        required : true
                    },                   
                    email: {
                        required : true,
                        email: true
                    },
                    phone: {
                        required : true,
                        minlength: 10
                    },                    
                    password: {
                        required : true                        
                    },
                    cpassword: {
                        required : true,
                        equalTo: "#password"
                    }
                },
            // set validation messages for the rules are set previously
                messages: {
                    username: {
                        required : "Username is required"
                        
                    },
                    fullname: {
                        required : "Full Name is required"
                    },                    
                    email: {
                        required : "Email is required",
                        email: "Enter a valid email. Ex: example@gmail.com"
                    },
                    phone: {
                        required : "Phone Number is required",
                        minlength: "Password must contain 10 numbers"
                    },                   
                    password: {
                        required : "Password is required"
                    },
                    cpassword: {
                        required : "Confirm Password is required",
                        equalTo: "Confirm Password must be matched with Password"
                    }                   
                }
            });
            $('#password').keyup(function() {
                $('#result').html(checkStrength($('#password').val()))
                })
                function checkStrength(password) {
                var strength = 0
                if (password.length < 6) {
                    $('#result').removeClass()
                    $('#result').addClass('short')
                    return '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Too short'
                }
                if (password.length > 7) strength += 1
                // If password contains both lower and uppercase characters, increase strength value.
                if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) strength += 1
                // If it has numbers and characters, increase strength value.
                if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) strength += 1
                // If it has one special character, increase strength value.
                if (password.match(/([!,%,&,@,#,$,^,*,?,_,~])/)) strength += 1
                // If it has two special characters, increase strength value.
                if (password.match(/(.*[!,%,&,@,#,$,^,*,?,_,~].*[!,%,&,@,#,$,^,*,?,_,~])/)) strength += 1
                // Calculated strength value, we can return messages
                // If value is less than 2
                if (strength < 2) {
                    $('#result').removeClass()
                    $('#result').addClass('weak')
                    return '<i class="fa fa-exclamation-circle" aria-hidden="true"></i> Weak'
                } else if (strength == 2) {
                    $('#result').removeClass()
                    $('#result').addClass('good')
                    return '<i class="fa fa-check" aria-hidden="true"></i> Good'
                } else {
                    $('#result').removeClass()
                    $('#result').addClass('strong')
                    return '<i class="fa fa-thumbs-up" aria-hidden="true"></i> Strong'
                }
            }
        });
    </script> 
</body>
</html>

Final controller  -  Register.php


<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Register extends CI_Controller {
 public function __construct()
 {
  parent::__construct();
  $this->load->model('User_model');
 }

 public function index()
 {
  $this->load->view('register');
 }

 public function checkUsername()
 {
  // check the username is already used one or not
  if($this->User_model->getUsername($_POST['username'])){
   echo '<label class="text-danger"><span><i class="fa fa-times" aria-hidden="true">
   </i> This user is already registered</span></label>';
  }
  else {
   // check the username length is greater than 5 or equal to 5
   if (strlen($_POST['username'])>=5) {
    echo '<label class="text-success"><span><i class="fa fa-check-circle-o" aria-hidden="true"></i> Username is available</span></label>';
   }
   else {
    echo '<label class="text-danger"><span><i class="fa fa-times" aria-hidden="true"></i> Username must contain at least 5 characters</span></label>';
   }   
  }
 }
 public function signUp()
 {
  $config['upload_path'] = './assets/images';   // uploading folder
  $config['allowed_types'] = 'gif|jpg|png|jpeg';
  $config['max_size'] = '2048000';   // max size in KB
  $config['max_width'] = '20000';    //  max resolution width
  $config['max_height'] = '20000';   //max resolution height
  // load CI libarary called upload 
  $this->load->library('upload', $config);
  // body of if clause will be executed when image uploading is failed
  if(!$this->upload->do_upload()){
   $errors = array('error' => $this->upload->display_errors());
   // This image is uploaded by default if the selected image is not uploaded
   $image = 'no_image.png';    
  }
  // body of else clause will be executed when image uploading is succeeded
  else{
   $data = array('upload_data' => $this->upload->data());
   $image = $_FILES['userfile']['name'];  //name must be userfile  
  }
        $this->User_model->insertUser($image);
        //set message to be shown when registration is completed
        $this->session->set_flashdata('success','<span><i class="fa fa-check-circle-o" aria-hidden="true">
   </i> User is registered!</span>');
        redirect('Register');  
 }
}

Final model  -  User_model.php


<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User_model extends CI_Model {
 // get username from database
 public function getUsername($username)
 { 
  // find the username matched with the input
  $this->db->where('username' , $username);
  $query = $this->db->get('users');
  // check whether there are matching records
  if($query->num_rows()>0){
   return true;
  }
  else {
   return false;
  }
 }
 // store a user
 public function insertUser($image)
 {
        $data = array(
         //assign user data into array elements
         'user_id' => $this->input->post('user_id'),
         'username' => $this->input->post('username'),
         'fullname' => $this->input->post('fullname'),
         'email' =>$this->input->post('email'),
         'phone' =>$this->input->post('phone'),
         'password' =>sha1($this->input->post('password')),
         'image' => $image
     );
  // insert data to the database
  $this->db->insert('users', $data);
 }
}

I think now you have made a nice registration form with a lot of front end validations! It will be very nice guys! Try with different inputs and enjoy!
Wait for another article and I'll be back soon...
Have a good day!




2 Comments

  1. PkDomain providing Hosting in Pakistan. Don’t need to go away if you looking for Web Hosting in Pakistan. You can get PK domains registration. We are providing high quality website hosting to personal and business websites in Pakistan. Pay a visit to our website at www.pkdomain.com.pk. You can also buy cheap reseller hosting in Pakistan from us. We Provide Reliable Web Hosting at affordable prices.

    ReplyDelete
  2. Visit my website in indonesia for get source code free and premium in matadeveloper.com

    ReplyDelete