Liferay AJAX Server Side Validations

Introduction:

Generally when we submit form we will do validations. This validation will be performed against used input based on our data validation policies.

We have two types of validations
  1. Client Side Validation
  2. Server Side Validation

Client side validation

Client validation performed using java script in the form. We have different client side validation java script libraries to do this job. We have many client side validation frameworks like jQuery validator, AUI validator.

Liferay also have one of the tag called <aui:validator/> to perform client side validations.

Follow the article for more about Liferay Client Side Validations


Server Side Validation

Some time client side validation not enough to do form validation and some time we need to check the data with existed data which is in database. Such scenario we need server side validations.

Generally server side validation performed after submit the form to the controller and there we will validate the data with database, based on that we will send errors back to the form.

If we do such a way, we need to preserve all fields which user already filled in the form. But once submit the form then all the data that user filled will be vanished after form submission.
We have two choices one is we need to preserve all the data that user already filled and bring back to form along with error messages.

Another one is use Ajax Validations. When we do AJAX server side validation we don’t bother about user filled data.

Generally we will send Ajax call to controller and we will do validation, based on validation we will return some string or JSON object as response then we will display error messages in the form .In this scenario we need not to submit form, instead of summit form we will send single or multiple user input values to controller there we do validation against data then return success or error message as response.

Liferay Server Side Validation

Same we will use Ajax calls to do service side validation in liferay portlet development. Liferay have very good AUI java scrip library so that we can simply use Ajax in Liferay.

We have AUI IO module to implement Ajax in Liferay we will use server resource method to prepare response and send the response back to jsp page.

AUI Ajax Example in Liferay

The following is simple Ajax Call Implementation in Liferay


<%@include file="init.jsp"%>
<portlet:resourceURL var="resourceURL">
</portlet:resourceURL>
<h1>Liferay AUI Ajax Call Example</h1>
<br/>
<h2><aui:a href="#" id="getUserdData" name="getUserdData" label="Get Userd Data"></aui:a></h2>
<br/>
<div id="userContent">
<table id="usersTable" border="1">
</table>
</div>

<aui:script>
AUI().use('aui-base','aui-io-request', function(A){
A.one("#<portlet:namespace/>getUserdData").on('click',function(){
// alert("Hi you have performed Click Event and Thank You");
var allRows="";
//aui ajax call
A.io.request('<%=resourceURL%>',
{
dataType: 'json',
method: 'GET',
data: { paranName: 'ParamValue' },
on: {
success: function() {
var data=this.get('responseData');
A.Array.each(data, function(obj, idx){
var tableRow='<tr><td>'+obj.screeName+'</td><td>'+obj.firstName+
'</td><td>'+obj.lastName+'</td><td>'+obj.email+'</td></tr>';
allRows=allRows+tableRow;
});
A.one('#usersTable').empty();
A.one('#usersTable').set('innerHTML',allRows);
}
}
});
});
});
</aui:script>


Server Resource Method for above Ajax Call


public class LiferayAUIAjaxAction extends MVCPortlet {
@Override
public void serveResource(ResourceRequest resourceRequest,
ResourceResponse resourceResponse)throws  IOException,
PortletException {
try {
System.out.println("====serveResource========");
JSONObject jsonUser=null;
JSONArray usersJsonArray=JSONFactoryUtil.createJSONArray();
List<User> userList=UserLocalServiceUtil.getUsers(1, UserLocalServiceUtil.getUsersCount());
for(User userObj:userList){
jsonUser=JSONFactoryUtil.createJSONObject();
jsonUser.put("firstName",userObj.getFirstName());
jsonUser.put("lastName",userObj.getLastName());
jsonUser.put("email",userObj.getEmailAddress());
jsonUser.put("screeName",userObj.getScreenName());
usersJsonArray.put(jsonUser);
}
PrintWriter out=resourceResponse.getWriter();
System.out.println(usersJsonArray.toString());
out.print(usersJsonArray.toString());
}
catch (Exception e) {
e.printStackTrace();
}
}
}


Note:

In the above example we simply use Ajax call to display list of users’ data in the page.

Download AUI AJAX Portlet



Server Side Validation using Liferay AUI Ajax

Now we will use AUI Ajax to implement server side validation.

Scenario:

Assume we have registration from and we have Screen Name and Email Address input fields.
When the user choose screen name or if user enter email address based on that we need to check with our database that is availability of email address and screen name, based on that we need to show error or success message to end user.

We have two fields when user enter and leave the fields then we will send AJAX call to controller and there we will validate screen name availability and email availability then we will show respective information to end user as validation messages.

Here we simple make red border to the fields if the screen name and email address not available. If available then we will make green border to the fields.

The following is code implementation

AUI Ajax Call in JSP page


<%@ include file="init.jsp"%>
<h2>User Registration</h2>
<portlet:actionURL var="registrationActionURL" windowState="normal"
name="createAccount">
</portlet:actionURL>
<portlet:resourceURL var="resourceURL">
</portlet:resourceURL>
<form action="<%=registrationActionURL%>"
name="<portlet:namespace/>userForm"
id="<portlet:namespace/>userForm" method="POST">
<b>Screen Name</b><br />
<input type="text" name="<portlet:namespace/>screeName" id="<portlet:namespace/>screeName" /><br />
<b>Email Address</b><br />
<input type="text" name="<portlet:namespace/>emailAddress" id="<portlet:namespace/>emailAddress" /><br />
<b>First Name</b><br />
<input type="text" name="<portlet:namespace/>firstName" id="<portlet:namespace/>firstName" /><br />
<b>Last Name</b><br /> <input type="text"
name="<portlet:namespace/>lastName" id="<portlet:namespace/>lastName" />
<br />
<input type="radio" name="<portlet:namespace/>sex" value="1">Male<br>
<input type="radio" name="<portlet:namespace/>sex" value="0">Female<br />
<b>Address</b><br />
<textarea rows="4" cols="50" name="<portlet:namespace/>address">
</textarea>
<br /> <input type="button" name="<portlet:namespace/>addUser" id="<portlet:namespace/>addUser"
value="Create Account" />
</form>
<aui:script>
AUI().use('aui-base','aui-io-request','aui-node', function(A){
var userEmailValidation=false;
var userScreenNameValidation=false;
A.one("#<portlet:namespace/>screeName").on('blur',function(){
//aui ajax call
var screeName=A.one("#<portlet:namespace/>screeName").get("value");
A.io.request('<%=resourceURL%>',{
dataType : 'json',
method : 'GET',
data : {
<portlet:namespace/>screeName :screeName,
<portlet:namespace/>cmd:'SCREENNAME'
},
on : {
success : function() {
var data = this.get('responseData');
var isScreenNameExist=data.screenNameExist;
//alert(isScreenNameExist);
if(isScreenNameExist=='true'){
A.one("#<portlet:namespace/>screeName").setStyle('border',
'1px solid red');
userScreenNameValidation=false;
}
if(isScreenNameExist=='false'){
A.one("#<portlet:namespace/>screeName").setStyle('border',
'1px solid green');
userScreenNameValidation=true;
}

}
}
});
});
A.one("#<portlet:namespace/>emailAddress").on('blur',function(){
var emailAddress=
A.one("#<portlet:namespace/>emailAddress").get("value");
A.io.request('<%=resourceURL%>',{
dataType : 'json',
method : 'GET',
data : {
<portlet:namespace/>emailAddress :emailAddress,
<portlet:namespace/>cmd:'EMAIL'
},
on : {
success : function() {
var data = this.get('responseData');
var isEmailExist=data.emailExist;
//alert(isEmailExist);
if(isEmailExist=='true'){
A.one("#<portlet:namespace/>emailAddress").setStyle('border',
'1px solid red');
userEmailValidation=false;
}
if(isEmailExist=='false'){
A.one("#<portlet:namespace/>emailAddress").setStyle('border',
'1px solid green');
userEmailValidation=true;
}

}
}
});
});
A.one('#<portlet:namespace/>addUser').on('click', function(event){
if(userEmailValidation==true&& userScreenNameValidation==true){
document.<portlet:namespace/>userForm.submit();
}
});

});
</aui:script>



Portlet Action Class with Serve Resource Method


public class RegistrationPortletAction extends MVCPortlet {
public void createAccount(ActionRequest actionRequest,
ActionResponse actionResponse) throws IOException, PortletException {
try {
String firstName = ParamUtil.getString(actionRequest, "firstName");
String lastName = ParamUtil.getString(actionRequest, "lastName");
String screeName = ParamUtil.getString(actionRequest, "screeName");
String emailAddress = ParamUtil.getString(actionRequest,
"emailAddress");
int studentGender = ParamUtil.getInteger(actionRequest, "sex", 1);
String address = ParamUtil.getString(actionRequest, "address");
// write logic to add data in database
System.out.println("====From submitted succesfully=====");
} catch (Exception e) {
SessionErrors.add(actionRequest.getPortletSession(),
"student-add-error");
e.printStackTrace();
}
}

@Override
public void serveResource(ResourceRequest resourceRequest,
ResourceResponse resourceResponse) throws IOException,
PortletException {
JSONObject jsonUser = JSONFactoryUtil.createJSONObject();
String cmd = ParamUtil.getString(resourceRequest, "cmd");
System.out.println("====serveResource===cmd====="+cmd);
String emailAddress = ParamUtil.getString(resourceRequest,"emailAddress");
String screeName = ParamUtil.getString(resourceRequest, "screeName");
if (cmd.equals("EMAIL")) {
emailValidation(resourceRequest,resourceResponse,emailAddress);
}
if (cmd.equals("SCREENNAME")) {
screenNameValidation(resourceRequest,resourceResponse,screeName);
}
}
public void screenNameValidation(ResourceRequest resourceRequest,
ResourceResponse resourceResponse,String screeName) throws IOException,
PortletException {
User user = null;
JSONObject jsonUser = JSONFactoryUtil.createJSONObject();
ThemeDisplay themeDisplay = (ThemeDisplay) resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);
try {
user = UserLocalServiceUtil.getUserByScreenName(themeDisplay.getCompanyId(), screeName);
if (user != null) {
jsonUser.put("screenNameExist", "true");
}
} catch (PortalException e) {
jsonUser.put("screenNameExist", "false");
} catch (SystemException e) {
jsonUser.put("screenNameExist", "false");
}
PrintWriter out = resourceResponse.getWriter();
out.println(jsonUser.toString());
System.out.println("=="+jsonUser.toString());
}
public void emailValidation(ResourceRequest resourceRequest,
ResourceResponse resourceResponse,String emailAddress) throws IOException,
PortletException {
User user = null;
JSONObject jsonUser = JSONFactoryUtil.createJSONObject();
ThemeDisplay themeDisplay = (ThemeDisplay) resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);
try {
user = UserLocalServiceUtil.getUserByEmailAddress(themeDisplay.getCompanyId(), emailAddress);
if (user != null) {
jsonUser.put("emailExist", "true");
} else {
jsonUser.put("emailExist", "false");
}
} catch (PortalException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
jsonUser.put("emailExist", "false");
} catch (SystemException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
jsonUser.put("emailExist", "false");
}

PrintWriter out = resourceResponse.getWriter();
out.println(jsonUser.toString());
System.out.println("=="+jsonUser.toString());
}
private static Log _log = LogFactoryUtil
.getLog(RegistrationPortletAction.class);
}


Download Liferay AJAX Server Side Validation Portlet



Environment:

Liferay IDE 2.x+Eclipse (Kepler) +Liferay Plugins SDK 6.2+Tomcat 7.x Liferay Portal Bundle

Deployment and its Working.

Download portlet you can source or war file to deploy into liferay portal as your convenient.

Once portlet successfully deployed drag the portlet in any desired page. Portlet is available in sample category name as Liferay Ajax Server Side Validation.

When you enter any screen name or email address already existed then input element bore become red color.

Portlet Screens:

User Registration Page



Related Links





Author
Share on Google Plus

About Meera Prince

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment