Wednesday, September 18, 2013

Dynamically validating input using java script in php code igniter

This is to simply validate input while you are typing in php/html using java script. I have tried this in Code Igniter framework with netbeans IDE 7.3 also.
As an example we will see how to validate a text box where only  positive numbers are allowed including zero. Later you can customize this code according to your requirements

Your html code for text box will look like this

<input type="text"  class="form_text" id="marks" name="marks" onkeyup="validatePositiveNumber(this.value,'errorMarks')"/>
                     <br/> <span id="errorMarks"></span>

here text box id name is "marks". you can give any name you like
I have used a span to display the error message. Its id is "errorMarks" where you can give any name

We need to use "onkeyup" event of the text box as we intend to validate its value each and every time user presses some key. I have given the function name as "validatePositiveNumber" which I'm going to write using javascript. The function takes 2 parameters current value of the text box(this.value) and span id to display the error message ("errorMarks")

Now it's time to create javascript. You can include following javascript inside head section or inside the same form as the text box

 <script>
            function isFloat(input)
            { 
                //to check float values. It checks each character

                var i;
                var j=0;//to count number of decimal points in the parameter

                for (i = 0; i < input.length; i++)
                {
                    // Check that current character is a digit(0-9) or dot
                    var c = input.charAt(i);
  
                    if (((c < "0") || (c > "9")))
                    {
                        if(c != ".")
                        {
                           //if it's not a digit or not "." return false
                            return false;
                        } 
                        else        
                        {
                             //if it's "." counting number of decimal points 
                            j++;
                        }     
                    }//end of if()
   
                }//end of for()

                // if all characters are digits n dots then make sure it has at most one decimal point.
                if(j>1)
                {
                    return false;
                }
                return true;
             
                //end of function isFloat()
            }


            function validatePositiveNumber(str,id)
            {
                // check whether it's empty
                if (str.length==0)
                {
                    document.getElementById(id).style.color = 'red';//error font color
                    document.getElementById(id).innerHTML="Please Enter the Value";//error message
                    return false;
        
                } 
                else if (!isFloat(str) || str.indexOf(".") == (str.length-1))
                {
                   //check whether it s not a positive float or containing decimal point at the very end

                    document.getElementById(id).style.color = 'red';//error font color
                    document.getElementById(id).innerHTML="Please Enter a valid value";//error message
                    return false;
                }
                else
                {
                    // when it's valid showing no error messages at all
                    document.getElementById(id).innerHTML="";
                    return true;
                }
                //end of function
            }
        </script>

That's it................Enjoy :)

Output immediately after you enter an invalid character 

Output immediately after you enter tab key and skip the text box

Further Reference :
on key events: http://www.w3schools.com/jsref/event_onkeypress.asp
more events:http://www.w3schools.com/jsref/dom_obj_event.asp


Code credit : I got this javascript code from one of my friends Mushthaq Rumy with little modifications
Hope it will be useful for you.

Web Services and Java Hibernate

This is about how to deal with web services specifically when you create the backend (dealing with database) using webservices. Assume some data to be inserted to the database is send inside json object by calling a webservice in the backend. Then it unwraps the data which is in the json object and insert them to database table via a POJO class. This may not be suitable for a complete beginner anyway it depends.

I will take sample codes from our project in which our vertical was hospital laboratory. I will consider a senario where data of a lab test result is wrapped in a json object and by calling a webservice it is sent from the front end to backend. Then the data is unwrapped and inserted to the relevant data table.

POJO class: Pain Old Java Object. These classes are very simple classes having few attributes and getters and setters for those attributes. They are specially used in frameworks. In out project we have one POJO class for each and every table in the database. So each and every column in the database table is an attribute of the POJO class. Further reading for POJO

Creating a POJO class:

In src folderInside your package(if any. In this example pojo classes are in "core.classes.lab" package) Create a normal java class using anyname(better use a name closely related to the actual database table). Add all the column names as attributes. To generate getters and setters (in eclipse)
-> click on the source code of pojo class at the end of all attributes
-> Select "Source" from main menu
->select "Generate Getters and Setters.."
->Tick all the attributes
-> Select "ok"

Now you code will look like this

package core.classes.lab;

public class Result {

/*
* This class corresponds to db table Result 
 */

int reportID;//primary key
LabOrder orderID;//a foreign key from LabOrder table
        Double chloride;
        Double serumSodium;
String remarks;

public int getReportID() {
return reportID;
}
public void setReportID(int reportID) {
this.reportID = reportID;
}
public LabOrder getOrderID() {
return orderID;
}
public void setOrderID(LabOrder orderID) {
this.orderID = orderID;
}
 public Double getSerumSodium() {
return serumSodium;
}
public void setSerumSodium(Double serumSodium) {
this.serumSodium = serumSodium;
}
public Double getChloride() {
return chloride;
}
public void setChloride(Double chloride) {
this.chloride = chloride;
}
        public String getRemarks() {
return remarks;
}
       public void setRemarks(String remarks) {
this.remarks = remarks;
}
}

Since there is a foreign key from labOrder table, there should be a class LabOrder which represent the labOrder table in the database.

Lets see how to create the corresponding xml mapping file
This mapping file map database table column to each and every attribute of the corresponding POJO class.

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="core.classes.lab.Result" table="labTestResult">

<id name="reportID" type="int" column="labTestResult_ReportID">
<generator class="increment" />
</id>

<many-to-one name="orderID" class="core.classes.lab.LabOrder"
not-null="true" cascade="all" unique="true">
<column name="labTestResult_LabOrderID" />
</many-to-one>

                <property name="serumSodium" column="labTestResult_SerumSodium" type="double" />
<property name="chloride" column="labTestResult_Chloride" type="double" />

<property name="remarks" column="labTestResult_Remarks" type="string" />


</class>
</hibernate-mapping>


  • class name: provide it with your package name as given above e.g. packagename.classname
  • table name: exact name as it is appear in the database
  • id tag: used to map the primary key column.
    • name: attribute name as it appears in the class
    • column: column name as it appears in the database table
    • type: data type in java
    • if it is an auto increment field only insert this tag <generator class="increment" /> 
  • one-to-one relationship mapping:
             <many-to-one name="orderID" class="core.classes.lab.LabOrder"
not-null="true" cascade="all" unique="true">
<column name="labTestResult_LabOrderID" />
</many-to-one>

    •   not_null and cascade has the same meaning as in the context of databases             
  • one-to-many relationship mapping: use above tag without  unique="true"
  • properties: maps all the rest of the attributes to columns 
    • name: attribute name as it appears in the class
    • column: column name as it appears in the database table
    • type: data type in java
After this you need to add this mapping file to hibernate.cfg.xml file where you have configured database name,password,host server details, etc
<mapping resource="lib/driver/lab/mappings/labEquipmentUser.hbm.xml" />


Lets see how to create a service class (in our case in a different package "lib.classes.labmodel") to unwrap the json object and feed data to a class object and send it to another class in order to insert them to database table

package lib.classes.labmodel;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import core.classes.lab.Result;//the corresponding POJO class
import lib.driver.lab.driverclasses.ResultServiceDriver;//service driver class
import org.codehaus.jettison.json.JSONObject;

@Path("/testResult")
public class ResultService {

@POST
@Path("/add")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_JSON)
public String addReport(JSONObject json) {

/*
* retrieve data from json object and pass it to service driver class
*/

int orderID;

try {

Result result = new Result();//POJO class object

orderID = json.getInt("orderID");//getting data from json

                        //getting relavant data from json and set them to POJO class object
result.setSerumSodium(Double.valueOf(json.getString("serumSodium").toString()));
                        result.setChloride(Double.valueOf(json.getString("chloride").toString()));
result.setRemarks(json.getString("remarks").toString());

/*sending POJO class instance along with the foreign key to service driver class in order to insert to the database table */                              
ResultServiceDriver resultServiceDriver = new ResultServiceDriver();

 resultServiceDriver.insertData(result, orderID);

return "ok";

} catch (Exception e) {
return e.getMessage();
}
}

}


  • @path() : define the path on how to reach to this service 
    • e.g. you need to add "/testResult/add" to the base url when you need to call the service in the browser or in the front end code
  • When calling this service a json object with necessary should be sent as input parameter to this
  • You will get errors since service driver class is not yet created. Just ignore them for the time being


Lets create a service driver class
in our case it is in another package " lib.driver.lab.driverclasses"

package lib.driver.lab.driverclasses;

import org.hibernate.Query;
import org.hibernate.Session;

import core.classes.lab.Result;
import core.classes.lab.SessionFactoryUtil;

public class ResultServiceDriver {

/*
* manupulate data in db table labTestResult
*/

Session session;
        
        //constructor
public ResultServiceDriver() {

session = SessionFactoryUtil.getSessionFactory().openSession();
}

// insert data to db table labTestResult
public void insertData(Result result, int orderID) {

session.beginTransaction();


//  for orderid ,attaching the foreign key POJO object
LabOrder labOrder = (LabOrder) session.get(LabOrder.class, orderID);

result.setOrderID(labOrder); 


session.save( result);//inserting data to the database table

session.getTransaction().commit();//commit transaction

CloseSession();


private void CloseSession() {
// TODO Auto-generated method stub
session.close();
}

}

That's it....
This shows how to insert values. Once you understand the pattern you just need to add methods to update,delete and select data in the driver class. Since this article is already lengthy I'm not gonna explain them here but you can get those details from following website.
http://www.mkyong.com/hibernate/hibernate-query-examples-hql/

Hope this article will be useful for you.










Bit of project experience


E Health -Laboratory

We were developing an e health system for hospitals in general where several groups take part in various tasks. There were three main verticals laboratory, pharmacy and OPD. There were research groups on usability, telecommunication etc and another group to develop framework and integrate the system. Since outcome of all the groups are going to be integrated ultimately as one product we were supposed to keep in touch with each other and follow common standards.


Architecture: SOA + MVC

As you know the architecture is the major factor for the success of a project. Combination of SOA (Service Oriented Architecture) and MVC (Model View Control) created a super architecture for our project. We used SOA instead of the Model part of the MVC. Therefore this architecture highly supports interoperability, flexibility, maintainability and scalability. 

We created front end using PHP. We used Code Igniter framework which is based on MVC architecture for that. We use MYSQL as DBMS. We connect front end and back end using restful web services. For that we used JSON and Java Hibernate.


Software and technologies we used:


Net Beans 7.2 (PHP)
Code Igniter
eclipse-jee-juno-SR2 (JAVA)
JBOSS Hibernate for java framework
Restful web services


Do s and Don't s


  • Though you are following agile software developing methodology where everyone is responsible for every task it is better to assign members for specific roles 
    • database admin for each group and another one for entire project
      • contribute to the integration of the entire database, maintain consistency with changing requirements and create and maintain unique standards and naming conventions for database tables, columns ,etc                         
    • one for take care of coding standards 
      • construct a common agreement and  make sure all the groups are following same naming conventions, same patterns and code structures, etc
  • Follow unique or well known standards
    • It helps a lot when it comes to maintain the project. When everything is up to standards any outsider can understand the coding within less time and less effort.
      • For database you can use a data catalog where each table and column is described in detail. (what is the purpose of each table/column why such a data type is used)
      • While following coding standards, put enough number of comments in the coding whenever it is necessary and use meaningful names for variables so that later anyone can understand it.
  • Better communication leads to success
    • Always have a better communication among groups, group members, with supervisors and client. It is a major factor for success or a failure of a project
    • Have frequent meetings with your supervisor and client. Make sure they get frequent updates about the current status of your project. Try to collect their feedback s much earlier so that you can avoid disaster situations at the later part of the project as well as it reduces the risk of failure
    • Use effective and quick communication methods. Though face to face communication is the best way when it is not possible use other means. 
    • You can use a face book page for entire group to share messages and a group blog. It is very practical 
  • Use tools 

  • It is better to have code camps once in a while where all the groups get together
    • It is really productive if all the groups gather in one room and have a sort of hackothon for may be 2-3 days. Timing is again important. Better time may be soon after exams where every member is free to put their best effort to the project. 
    • It helps to solve lot of issues and incompatibilities among groups very efficiently and effectively
    • It helps to keep up with other groups. If two groups use different code for the same task you can select the better one and make it as the standard one so that it helps to develop a better project as well as to keep the consistency. If a group in your project is already using a code that you want, no need to re invent it just use it.
    • It also gives a privilege to share knowledge and experience among groups and increase mutual understanding and friendship. 
  • It is really nice to name a common location for all the groups to come and work when they are free
    • It encourages better communication among groups
    • Otherwise each group works here and there and it will waste time to decide where to get together each time
  • Don't wait till the later stage of the project to integrate the ER while individual groups working  on their own ER
    • It is always better to as soon as you finished with your individual group ERs after requirement gathering, integrate the ERs and create a common ER for the entire project before start coding based on the individual group ER. If not, at a later stage you will have to change your entire coding etc which is both wasting of time and effort
  • Don't wait till the later stage to get feedback from the client/end users although they may not clear about what they really want
    • At the later stage when they see the product they may need lot of changes. If we can get their feedback from the early stages by using prototype etc we can develop a product which satisfies them more
  • It's better to have a proper research on what end users actually need, their preferences and what they don't like in details before starting the project.
  • Stress management
    • When working together it is normal to have arguments, disputes etc and specially near deadlines everyone get stressed so it is always better to be patient and avoid such situations.  Not only learning new technologies, learning to deal with different types of people is also an essential part in a project. It is better to allocate a little time to have some fun as a group once in a while. It helps to develop team spirit, increase mutual understanding and helps to develop a good environment to work.

hope it will be useful for your projects in the future...

Display remarks on input dynamically with validation

This is to display remarks on input while you are typing in PHP/HTML using java script. It also validate the input dynamically. I have tried this in Code Igniter framework with Netbeans IDE 7.3 also. I recommend this article even for a beginner as it explains everything in a clear manner.

 As an example assume you need to enter white blood cell count (WBC) in a lab result form. Though you are allowed to input any positive number there is a reference range for an healthy person (4000-11000). So if it is  below minimum value(4000) you can display a remark "Low" and if it is above maximum value (11000) you can display "High" otherwise "Normal" while entering the value. Refer the video given below to check how output behaves.





If necessary you can visit this post before reading this as I have advanced the same concept.dynamically validating input
Your html code will look like this

 <td>   

       <input type="text"  class="form-control" id="input1" name="input1"           onkeyup="validatePositiveNumber(this.value,'error1',10000,45000,'remarks1')"   /> 

        <br/> <span id="error1"></span>

</td>
 <td>
                 
         <label for="rangeValues">10000-45000</label>
         <br/> <span id="remarks1" ></span>

  </td>

So with the basic html knowlege you already know that I have created a table and inside that table inside a row as two table data <td> I am gonna apply above coding.

Inside 1st <td>:
I have created a text box. For the name and id you can give any name you like.
I have used a span to display the error message for validation errors. Its id is "error1" where you can give any name
function:
We need to use "onkeyup" event of the text box as we intend to validate its value each and every time user presses some key. I have given the function name as "validatePositiveNumber" which I'm going to write using JavaScript. The function takes 5 parameters current value of the text box(this.value), span id to display the error message ("error1"), minimum value then maximum value of the range which are numbers(10000,45000) and  span id to display the remarks ("remarks1") which is in the 2nd table data <td>

Inside 2nd <td>:
There is a label just to display the reference range values and a span to display remarks

Now it's time to create JavaScript. You can include following JavaScript inside head section or inside the same form as the text box

 <script>
            function isFloat(input)
            { 
                //to check float values. It checks each character

                var i;
                var j=0;//to count number of decimal points in the parameter

                for (i = 0; i < input.length; i++)
                {
                    // Check that current character is a digit(0-9) or dot
                    var c = input.charAt(i);
  
                    if (((c < "0") || (c > "9")))
                    {
                        if(c != ".")
                        {
                           //if it's not a digit or not "." return false
                            return false;
                        } 
                        else        
                        {
                             //if it's "." counting number of decimal points 
                            j++;
                        }     
                    }//end of if()
   
                }//end of for()

                // if all characters are digits n dots then make sure it has at most one decimal point.
                if(j>1)
                {
                    return false;
                }
                return true;
             
                //end of function isFloat()
            }


            function validatePositiveNumber(str,idError,min,max,idRemarks)
            {
                // to validate input number and display reference remarks
                //idError is to display error and idRemarks is to display reference remarks

                // check whether it's empty
                if (str.length==0)
                {
                    document.getElementById(idError).style.color = 'red';//error font color
                    document.getElementById(idError).innerHTML="Please Enter the Value";
                                                                                              //error message
                    document.getElementById(idRemarks).innerHTML=""; //for reference remarks
                    return false;
        
                } 
                else if (!isFloat(str) || str.indexOf(".") == (str.length-1))
                {
                   //check whether it s not a positive float or containing decimal point at the very end

                    document.getElementById(idError).style.color = 'red';//error font color
                    document.getElementById(idError).innerHTML="Please Enter a valid value";
                                                                                                //error message
                    document.getElementById(idRemarks).innerHTML=""; //for reference remarks
                    return false;
                }
                else
                {
                    // when it's valid showing no error messages at all
                    document.getElementById(idError).innerHTML="";
                 
                    //for reference remarks 
                    if(str<min)
                           {
                               document.getElementById(idRemarks).style.color = 'orange';
                               document.getElementById(idRemarks).innerHTML="Low";   
                           }
                    else if(str>max)
                           {
                               document.getElementById(idRemarks).style.color = 'orange';
                               document.getElementById(idRemarks).innerHTML="High";   
                           }
                     else {
                              document.getElementById(idRemarks).style.color = 'black';
                               document.getElementById(idRemarks).innerHTML="Normal";      
                           }

                    return true;//regardless of remarks now since the input is valid we return true
                }//end of else
                //end of function
            }
        </script>

That's it................Enjoy :)

Further Reference :
on key events: http://www.w3schools.com/jsref/event_onkeypress.asp
more events: http://www.w3schools.com/jsref/dom_obj_event.asp

Hope it will be useful for you.

Simple and easy validation for html text boxes

This is simply to validate html text boxes for a beginner without using complex JavaScript codes. I have tried this in php Code Igniter framework in NetBeans IDE 7.3 as well.

Your html code for text box will look like this

<input type="number" min="0" max="100"  class="form_text" id="marks" name="marks" required />

Using min and max properties you can minimum and maximum value allowed for a particular text box

required  ,does not allow empty text boxes

type="number"  ,allows positive and negative integers including 0

type="number"  step="any" , allows positive and negative decimal values including 0

type="text"  , allows any character thus you need to verify it by your own. Using min and max properties with this doesn't make any sense.

(specifying  min, max, required and type properties are optional)