wood burning stoves 2.0*
The moose likes Servlets and the fly likes What is good practice for FORM VALIDATION ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "What is good practice for FORM VALIDATION ?" Watch "What is good practice for FORM VALIDATION ?" New topic
Author

What is good practice for FORM VALIDATION ?

maha anna
Ranch Hand

Joined: Jan 31, 2000
Posts: 1467
Currently I am developing a web application which has many html forms where user enters data. I don't use javascript for form validation at the browser itself. I validate the inputs at the server end. At present I developed the appln assuming the user enters all the correct and neede data in correct format and tested the functionality of the web appln. I left out the VALIDATION PART to do it latter.
Now I left out with the form validation part which I don't like to do at all. But we HAVE TO validate the dates,mail address, phone nos etc and all. Isn't? Can anybody has found a good practice for this part? I think we can separate the validation part inside another class. The servlet just calls the validation class by passing the request as parameter. I am not sure about this part. I have to do some more thinking to make this process MORE ELEGENT AND MODULAR. If the user didn't enter 5 out of 10 NEEDED FIELDS we have to go back to user with the already typed data with the MISSED FIELDS HIGHLIGHTED. How we go about doing this part?
Can anyone give some idea about the general and good practice for form validation you all use for production appln? Also if any already exising code/tools for Date/Email/Phone other types of user input validation will be more useful.
Thanks a lot.
regds
maha anna
[This message has been edited by maha anna (edited October 26, 2000).]
Sandeep Jain
Ranch Hand

Joined: Oct 25, 2000
Posts: 124
Hi,
Anything to do with client side validation is preferred in javascript. The simple reason for this is as follows :-

First the data goes to the server checks if it is correct, if not it sends the data to the client again to validate .
In this entire process we are putting unnecessary burden on the server and because of this the server speed will be affected and will take more time .
So it is adviceable to do maximum validation by entering all the fields ,and checking the format of emails, date validations, etc in javascript.
------------------
Sandeep Jain


Try and Try Till u succeed<br /> <br />Sandeep Jain
Waliullah Memon
Greenhorn

Joined: Sep 21, 2000
Posts: 8
Hi Maha , server side Form Validation has been explianed in a very nice way in "Web development with JSP".An example from this book is here which validates for email, ssn and Last, First name.
regards
Wali

package com.taglib.wdjsp.commontasks;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class FormHandlerServlet extends HttpServlet {

public void service(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
Vector errors = new Vector();
String name = req.getParameter("name");
String ssn = req.getParameter("ssn");
String email = req.getParameter("email");
if (! isValidName(name))
errors.add("Please specify the name as Last, First");
if (! isValidEmail(email))
errors.add("Email address must contain an @ symbol");
if (! isValidSSN(ssn))
errors.add("Please specify a valid SSN number, no dashes");

String next;
if (errors.size() == 0) {
// data is OK, do whatever
// dispatch to wherever
next = "thanks.jsp";
}
else {
// data has errors, try again
String[] errorArray = (String[])errors.toArray(new String[0]);
req.setAttribute("errors", errorArray);
next = "form.jsp";
}
String base = "/commontasks/";
RequestDispatcher rd;
rd = getServletContext().getRequestDispatcher(base + next);
rd.forward(req, res);
}
private boolean isValidSSN(String ssn) {
// check for 9 characters, no dashes
return (ssn.length() == 9 && ssn.indexOf("-") == -1);
}
private boolean isValidEmail(String email) {
// check an "@" somewhere after the 1st character
return (email.indexOf("@") > 0);
}
private boolean isValidName(String name) {
// should be Last, First - check for the comma
return (name.indexOf(",") != -1);
}
}
//now the jsp part
<jsp:useBean id="form" class="com.taglib.wdjsp.commontasks.FormBean">
<jsp:setProperty name="form" property="*"/>
</jsp:useBean>
<html>
<body bgcolor="white">
<%
String[] errors = (String[])request.getAttribute("errors");
if (errors != null && errors.length > 0) {
%>
<b>Please Correct the Following Errors</b>
<ul>
<% for (int i=0; i < errors.length; i++) { %>
<li> <%= errors[i] %>
<% } %>
</ul>
<% } %>
<form action="<%= request.getContextPath() %>/servlet/FormHandlerServlet" method="post">
<input type="text" name="name"
value="<jsp:getProperty name="form" property="name"/>">
<b>Name</b> (Last, First)<br>
<input type="text" name="email"
value="<jsp:getProperty name="form" property="email"/>">
<b>E-Mail</b> (user@host)<br>
<input type="text" name="ssn"
value="<jsp:getProperty name="form" property="ssn"/>">
<b>SSN</b> (123456789)<br>
<p>
<input type="submit" value="Submit Form">
</form>
</body>
</html>
//and the bean
package com.taglib.wdjsp.commontasks;
public class FormBean {

private String name;
private String email;
private String ssn;

public FormBean() {
name = "";
email = "";
ssn = "";
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
public String getSsn() {
return ssn;
}
}
maha anna
Ranch Hand

Joined: Jan 31, 2000
Posts: 1467
Thanks Sandeep and Wali.
Sandeep,
I thought about it a lot. The reasons you say is the compelling ones to make the validation at the browser itself.
The main reason I decided to go for server side validation is , latter if there is any change in my business rules, if the validation would have been at the server side, just making the change in server code itself enough. But if I would have put them at the client end , I need to change all the affected front ends. The client side may be a browser or a custom application. If the request would have come from the custom appln, then I need to make the changes in all the clients. This is the main reason. Another one is to make the client as thin as possible.
Wali thanks for your info. I go through the code and see.
regds
maha anna
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
Personally, I always prefer server-side validation if at all possible. It's much more powerful and maintainable. Use server-side validation if the customer will accept it, and if the response time from the server is quick enough so it's not too annoying.
If client-side JavaScript validation is really needed, try and isolate it into one or more separate javascript files, used by all the pages in question. This will help to keep it at least a little bit manageable.
There are some "gotchas", which everyone working on form validation comes up against at one time or another. Here are a few hints.
1. If you are doing JavaScript validation, be very wary of browser differences. And I don't just mean Netscape or IE, I mean which version of which browser. You really must test on every version that your clients will be using; sometimes a minor version change can have a giant impact on this sort of code.
2. Do lots of experiments before claiming to your customers that something can be done. Just because it's in the JavaScript spec, doesn't mean it's possible in any or all of the actual browsers. Try getting Netscape to set a background color in a form field, for instance...
3. If using server-side validation, beware that most browsers don't send back empty fields. This may seem fine if all the fields start off blank, but if you are writing a pre-populated form for someone to edit and re-submit, you will get complaints that they can never delete a field! There are two common ways of solving this, and several wierd ones.
The first common way is to "tweak" all form fields from JavaScript just before a form is submitted (by adding a known character to the end of the field which can be stripped off at the server, for example). This will ensure that all fields are non-empty, so they all get sent.
The second common way, which is particularly appropriate if the form pages are dynamically generated, is to keep a "note" of which fields should be returned at the server, and set any which are not returned, to an empty value.
As for the wierd ways, one project I worked on went to the trouble of putting an Applet on the page which contained a Hashtable of values, and intercepted the form's submit action and did it instead. Much too complex for my liking ...


Read about me at frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
maha anna
Ranch Hand

Joined: Jan 31, 2000
Posts: 1467
Thanks Frank. Your experience talks. I take a note of your suggestions.
regds
maha anna
Tony Alicea
Desperado
Sheriff

Joined: Jan 30, 2000
Posts: 3222
    
    5
I agree with Frank. JavaScript implies an "intelligent client" when the philosophy in e-commerce should be "Thin Client".
What if users have JavaScript disabled?

Tony Alicea
Senior Java Web Application Developer, SCPJ2, SCWCD
S Chandra Mohan
Ranch Hand

Joined: Oct 19, 2000
Posts: 75
Hi maha,
Iam working on a sales project. Normally we do date validations and others in java script itself.
I u have only few values to be checked
u can doit by passing them from servlet into javascript as an array or so (While deploying html ).
this will help a lot.
as we can minimize server interaction and also can validate data before submitting.
Hope u liked it.
Regards
Mohan


Have a wonderful day and wish u success<p>S Chandra Mohan<br />sc_mohan_us@yahoo.com
Rajpal Kandhari
Ranch Hand

Joined: Aug 26, 2000
Posts: 126
Hello Mohan,

What you r saying is sounding intresting. Well i would also like to make my client as thin as possible and since till now i only know servlet, Jdbc and JavaScript i would like to ask you to post a code to support what you r saying.
Since you have worked on such things I am sure that it will not be a pb. for you.

Regards,
Raj.


Regards,<P>Raj.<BR>-------------------------<BR>Afforts should be Appriciated.<BR>-------------------------
S Chandra Mohan
Ranch Hand

Joined: Oct 19, 2000
Posts: 75
hai raj,
u can take the value of the variable directly into javascript
like
out.println(" function valchk(){ ");
out.println(" var sampval = " + mservval + " ; ");
.....
or u can directly check like
out.println(" if(document.myhtm.t1.value = '"+mservval+"'){ ");
.
i think this can solve ur problem much.
If u still need more feel free to contact.
all the best
bye
mohan
maha anna
Ranch Hand

Joined: Jan 31, 2000
Posts: 1467
Thanks Mohan for your input.
regds
maha anna
Ira Jain
Ranch Hand

Joined: Sep 06, 2000
Posts: 70
Hi,
I have a doubt related to above.I have a Javascript-HTML form where parts of it are made visible/invisible depending upon the button I click.I have to call a servlet on one of them to do some server-side processing. I am not sure how to do this .Will be really obliged if somebody could help me with it .
Thanx in advance
Ira
------------------
maha anna
Ranch Hand

Joined: Jan 31, 2000
Posts: 1467
In the Form 'Action' value you write the url like this. Basically you href to the servlet's url in a href link OR in the Action part of a Form. Here I used www.wenappcabaret.com as an example.
regds
maha anna

Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
I also agree with Frank about JavaScript. If you do decide to use it you can never rely on the JavaScript. The application should always assume that the data must be validated even if you are using JavaScript. Consider JS a little bonus for the user to speed up processing and not a critical piece of your application.
As to Waliullah, in my opinion that is exactly the wrong way to do data validation. The servlet should have no knowledge of business rules. To me that is so critical in a well designed application that it bears repeating... The servlet should have no knowledge of business rules.
The servlet should be for presentation of data only. What if at some point you decide to support foreign phone numbers... oops, every servlet that accepts a phone number must be changed. What if the users love your application so much that they want you design a version that can be used by a web-enabled phone... oops, now I need to go through all my servlets to rediscover my business rules.
The servlet should extract the data and pass it to a business-rule class that can handle the processing of the data from that servlet. Communication should, of course, be done by exchanging classes. You build a class containing the data from the form, pass it to the business rules class which then processes the data (perhaps passing requests to database classes) and builds a response class for the servlet.
If this sounds something like EJBs with session and entity beans, that is because it is the same architecture without the EJB server. This is the best architecture for splitting functionality and allowing classes to be very specialized and thus much easier to maintain.


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
maha anna
Ranch Hand

Joined: Jan 31, 2000
Posts: 1467
Thomas,
I kindly request your opinion on my code. THis is how I am writing at present.
1. In any servlet, I code from doGet(..) and doPost calls doGet(..).
2. In doGet(..), I check what the request means, and call the correponding action_for_****(..) method which is inside the same servlet.
3. In this action method, I first validate the request param values. But the servlet DOESN'T have the business logic in it. What it does is, it just passes the 'request' obj to a 'WorkerBean'.
4. The WorkerBean is nothing but a class which has all the form parameters as its members and the corresponding validation logic for each member(formParameter). It has the overall validateForm() method.
5. What the servlet does is it creates a WorkerBean by passing the request as param and then calls the .validateForm() method.
6. This .validateForm() method returns a Vector of errors.
7. The servlet just checks the size of the returned error vector and if it is 0 then takes the OK action , if >0 calles an errorPage which embeds the Vecror of errors and sent back to User.
So What I do is I write one WorkerBean for everyForm to be validated and the business logic in inside the WorkerBean.
Does this sound good? If anything to be considered for a scalable appln, please inform. Once again I appreciate your feedback. I know you DO NOT LIKE jsp. Please ignore the jsp part and consider the validation part.
regds
maha anna


[This message has been edited by maha anna (edited November 01, 2000).]
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
How I love to see these tiny little servlets!
The only thing I would do differently is that i would not pass the HttpServletrequest object to the WorkerBean (I love that name... makes me think of worker bees). Instead I would create a separate class and extract the individual itmes from the form into that class. The reason being that if you decide to create a new version of your app for some other device you can write your presentation logic to produce the same class even if it doesn't have an HttpServletRequest object. Imagine if you produce an applet version that talks to a servlet via object passing (I have an in-house application that works this way). As long as this version communicates with the WorkerBean using the same class as the regular servlet version, you can use the original WorkerBean.
Prasad Charasala
Ranch Hand

Joined: Nov 02, 2000
Posts: 67
Hi Maha,
While roaming in the internet world, some how I landed here today and after reading the posts here and I find people here are so helpful, so I immediately registered today.
Coming to your post, I think it is good approach but still you can improve that.
What happens if you have too many "Request Types"? You may have to code too many if-else conditions in doGet method, which will be difficult to maintain. What happens if one more request type adds on to your application in future? You may have to modify your servlet and recompile it with one more if condition.
I suggest you to use "Reflection" in this case. Let your servlet be simple.
1. Have one "WorkerBean" class, which will be have one method suppose execute() which returns you back an HashMap object.
2. This hashmap object will have the jsp page name and other dynamic values to fill into the jsp.
3. Servlet gets the jsppage name from the hashmap object, forwards the request to that JSP along with the hashmap object.
4. Jsp gets all the dynamic name-value pair from the hashmap object and fills wherever necessary.
5. In the workerbean class get the "requestType" ( requestType should return you class name ).
6. Get an instance of that class(Let me call this as HelperBean) using reflection in java and call the appropriate method of that class which returns you again an hashmap object.
7. Every "HelperBean" class will be having logic to validate the form data within it. (So we can write one HelperBean class for each form, every workerbean should know how to validate its own form).
In this way your servlet will just acts like dispatcher with minimal code within it without business logic. All the business logic will be in the "HelperBean" classes. Presentation only will be the job of jsp. The data link between "HelperBean" and your Jsps will only be the HashMap object. (You can choose XML also in this place.)
Because of my bad writing skills, if you want further explanation or code, I can send it.

------------------
Prasad


<B>Prasad</B>
Brian Nice
Ranch Hand

Joined: Nov 02, 2000
Posts: 195
This is an interesting article dealing with this subject at www.javaworld.com dealing with form validation using XLM. So far two parts have been written and there are more to come. The URL to part one is http://javaworld.com/javaworld/jw-09-2000/jw-0908-validation.html
HTH
Brian
maha anna
Ranch Hand

Joined: Jan 31, 2000
Posts: 1467
Thnak you Thomas, Prasad and Brain.
Thomas,
Good point. I should have thought about it. Thank you.
Prasad,
I get a fair idea about what you say. If it is not much of a problem for you please post sample code for your improved approach so that it will be helpful for all of us here . If the code is very long please send to mahaanna@yahoo.com and I try to skim the logic and I post here in this thread so that this discusision will be more useful. Thanks a lot.
Brain,
Thanks. I go through the article and see.
regds
maha anna
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
I know you DO NOT LIKE jsp. Please ignore the jsp part and consider the validation part.
Actually, the more I have been working with them, the more I like them. As long as their use is tightly controlled and minimal Java code is used in them they can work well. I still think that they aren't perfect and have serious shortcomings, but they are better than just about every other solution I have seen until now.
V Srinivasan
Ranch Hand

Joined: Aug 16, 2000
Posts: 99
Can we call a servlet in onchange attribute of the HTML text field tag so that when a user filling in the form, before reaching submit, a servlet can validate the value of the text field Where the fields splited in different forms e.g. form1 for name, form2 for email address, form3 for ssn etc. Hence when he submits, according to the validation, through another servlet send a page to the client to repost duly filled wherein displaying the accepted fields (setting setValue attribute) and unfilled fields. Is this possible to do, I have not tried, just the idea triggered and I posted to this thread.
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Hi maha,
I think the best form of validation in the forms instead of validation using the javascript though it happens to be the first choice is to Use XML. THis is a server side validation where U have a method which takes the information from the XML file, where Ur fields are identified by the <PAGE_NAME><FIELD_NAME> Type tags. Hence it helps you in getting urself relief of recoding the simple validatons like isCurrency or isData by using a common XML with all basic validations defined along with corrosponding java which contain the validations.
thanks.
Sean MacLean
author
Ranch Hand

Joined: Nov 07, 2000
Posts: 621
What a great topic, all to often not addressed! From a design prespective, 'Form' validation is a bit misleading. If the application is processing form data that will ultimately be stored and retieved (ie. DB ), then the data should be validated from the input screen right down to the DB table contraints. This may seem like over kill, but we must note that data integrity is paramount to an appication's stability. If there is any possiblity of 'bad' data getting past or around a validity check, then plug that hole. In term's of how to handle the 'front end' validation, here's is a nice article to check out (it's a different article than the one above and is similar to what Prasad describes above. We've recently used this method in a massive web application and it worked great ).
http://www.javaworld.com/javaworld/jw-03-2000/jw-0331-ssj-forms.html
Sean
V Srinivasan
Ranch Hand

Joined: Aug 16, 2000
Posts: 99
Sean,
Thank you very much. Really that article clears lots of doubts.
Thanks.
Maha,
Please go thro, it is really interesting and would help you.
Thanks.
Eric Spery
Greenhorn

Joined: Nov 19, 2000
Posts: 5
V Srinivasan,
If you absolutely must validate your form on the client side, and it's been my experience that this can be extremely problematic, then you might want to try this old CGI trick. Add a hidden frame to your page, a zero-width/height frame. Use your client side JavaScript to post your form results to a servlet in this frame, and parse the results from your originating frame. It's a kludge, but it has its uses.
regards,
eric
V Srinivasan
Ranch Hand

Joined: Aug 16, 2000
Posts: 99
Eric,
Your suggestion sounds interesting. Could you pls post a few line of codes, so that I can understand how it flows.
See, my aim is not to put burdon on client side or server side, but to utilise client's idle time and validate the value of that particular tag parallely, and repost to client a form with highlighting his invalid inputs on submit or send a notice of success.
I assume while filling the form definitely client consume some considerable amount of time, I want to utilise that... and I don't want him to wait long for validating his inputs.
In this case, I want to check according to my business rule, including its uniqueness. Is it possible?
Regards,
[This message has been edited by V Srinivasan (edited November 21, 2000).]
[This message has been edited by V Srinivasan (edited November 21, 2000).]
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
hi everybody,
I was just searching for something in the net and suddenly landed among this interesting discussions.I would like to include my question into this. I am doing an application based on portal architecture using JSP,EJb and things..
I need to do a date portal which is nothing but date of birth field where the user is allowed to enter or edit and submit the date entered to be stored in the database.can anyone of you suggest how to proceed on this? If i have a text field for the date column, how do i validate?
 
 
subject: What is good practice for FORM VALIDATION ?