Solved

Good Form Validating Techiques Please!!!

Posted on 2004-03-29
10
190 Views
Last Modified: 2013-12-24
Hello, I would like some good working knowledge of form validation.  I have been doing some searching through past questions and its hard to get a decent read on what the best techniques are.  I have some forms on my site that use code I received from past questions and even though they work 95% of the time, it seems that there are those problems with older browsers or disabled javascript browsers that defeat the client-side validating.

So what are the best techniques to use to ensure that I able to work with just about all browsers and not worry about disabled javascript browsers.

Thank you for your help.

Jeff
0
Comment
Question by:jeffmace
  • 2
  • 2
  • 2
  • +2
10 Comments
 
LVL 17

Accepted Solution

by:
Tacobell777 earned 200 total points
ID: 10710002
Rule number one, ALWAYS do server-side validation ALWAYS ALWAYS ALWAYS.

the Javascript validation should be there to assist the user and save resources, for example, if you do not have JavaScript for validation then a request has to me to the server each time to check, this is not only a waste but also time consuming for the user.

How I handle it?

I create an XML file that describes the form fields, i.e. max length, min length, required, not required, regular expression, friendly name etc. This I then use to auto generate server-side checking and validation but also for client-side.

If you want to do proper validation and filtering you need to look into using regular expressions.
0
 
LVL 11

Assisted Solution

by:hart
hart earned 100 total points
ID: 10711343
Tacobell is correct, you should always have server side checks too..

But also have javascript checks, it looks more friendly [the prompte and all]..

1. when ever you have a form write a function onsubmit="return functionname()"

2. when you are calling a function on an href always write on the onclick event and not on the href
    i.e <a href="#" OnClick="functionname();return false;">, don't ever forget the return false after the function name otherwise the href # will get fired.

3. See what we use to do is as soon as the user logs in we used to check wether javascript is enabled or not, if not then we used to write on top of the page that the site may not function properly if javascript is disabled.

to check it just put the words inside <noscript block.

form validations are the tricky part, i have always created js files and written down the long scripts in them.
and have always tried keep the functions coomin accross pages..

Hope these tips help

Regards
Hart
0
 
LVL 17

Assisted Solution

by:anandkp
anandkp earned 100 total points
ID: 10711347
hi Jeff

1. decide what kinda users ur targetting : this wld help a gr8 deal to decide what kinda scripts u need to use !

2. like tacobell mentioned above : server side validations are a must - NO MATTER WHAT

3. wrt the timings u have to design the flow/code .. decide if u wanna go with CFFORMS [Built in Javascript]  or FORM [user defined scripts]

4. Generally now-a-days all users have javascripts enabled ... so using it wld help them for quick validations & avoid back-to-back server submission & processing as mentioned by tacobell.

5. U also have HTML related form validations .. wherein without using a javascript or cfscript - u can put a chk on form fields ... it uses the "Hidden" -> "fieldname_required" notation. use that - that shld be very handly for simple checks & range values.

rest it all depends on what u feel comfortable with & how u design things ... the users will eventually use what u want them to use ... :)

Cheers
Anand
0
 
LVL 11

Expert Comment

by:hart
ID: 10711351
sorry a typo i meant "common"and not "coomin" :-)

Regards
Hart
0
 

Author Comment

by:jeffmace
ID: 10712672
Thank you all for your tips.  Hart or anyone.  I was wondering if its possilbe to show an example of how you actually code this.  I guess I still get slightly confused on how you combine serverside and client side scripts.  As in Harts example.  It still looks like client side so what server side are you using.  Below is code from a page that I think some of you helped design and like I said in the beginning, it works pretty much all the time, but yet i see some of the records are not filled out or of the wrong format when i look in my database.  If you see something wrong with the code below please point it out.  I am not s JavaScript guru.  But I am looking to learn if there is a better way to combine the two validation schemes to insure that I get the proper data, plus learn better coding techniques

FORM CODE:
onSubmit="return _CF_checkCFForm_1(this)"


CODE:
<script type="text/javascript">
<!--
function validPhone(strFieldName){
    var strValue = strFieldName.value;
    var objRegExp = /^\d{10}$/;
    return objRegExp.test(strValue);
}
function compareFields(strValue,strValue2){
   return strValue == strValue2;
}
function hasValue(strFieldName){
     var strValue = strFieldName.value;
          strValue = strValue.split(" ").join("");
     if(strValue == ""){
          return false;
     }
     return true;
}
function hasSelection(strField){
  return strField.selectedIndex > 0;
}
function isEmail(strFieldName){
     var strValue = strFieldName.value;
    var objRegExp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return objRegExp.test(strValue);
}

function validateForm(fObj){
     var err = "";
     if(!hasValue(fObj["form_fname"])){
         err += "- First Name\n";
         switchStyle(fObj["form_fname"])
       }
     if(!hasValue(fObj["form_lname"])){
          err += "- Last Name\n";
              switchStyle(fObj["form_lname"])
     }
     if(!hasSelection(fObj["form_designation"])){
          err += "- Designation\n";
              switchStyle(fObj["form_designation"])
     }
     if(!hasSelection(fObj["form_specialty"])){
          err += "- Specialty\n";
              switchStyle(fObj["form_specialty"])
     }
     if(!hasValue(fObj["form_city"])){
          err += "- City\n";
              switchStyle(fObj["form_city"])
     }
     if(!hasSelection(fObj["form_state"])){
          err += "- State\n";
              switchStyle(fObj["form_state"])
     }
     if(!hasValue(fObj["form_zip"])){
          err += "- Zip\n";
              switchStyle(fObj["form_zip"])
     }
     if(!isEmail(fObj["form_email"])){
          err += "- Email\n";
              switchStyle(fObj["form_email"])
     }
    if(!validPhone(fObj["form_phone"])){
         err += "- Phone Number\n";    
             switchStyle(fObj["form_phone"])
    }
     if(!hasValue(fObj["form_password"])){
          err += "- Password\n";
              switchStyle(fObj["form_password"])
     }
     if(!hasValue(fObj["form_password2"])){
          err += "- Verify Password \n";
              switchStyle(fObj["form_password2"])
     }
    if(!compareFields(fObj["form_password"].value,fObj["form_password2"].value)){
         err += "The password fields do not match\n";
    }
     if(err != ""){
          alert("The following fields contain errors:\n\n"+ err);
               return false;
     }
   return true;
}

function switchStyle (theField) {    
     {
         strRow="TR" + theField.name;
     }
    document.getElementById(strRow).style.backgroundColor='FFDF62';
}

function resetColour(obj){
    strRow="TR" + obj;
     document.getElementById(strRow).style.backgroundColor='ffffff';
}    
// -->
</script>
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 17

Expert Comment

by:anandkp
ID: 10713977
I guess u've used CFFORM for generating this script !
This is client side error checks that u have :

For having server checks - u'll need to use it things like like

<CFIF isdefined('form_field') AND Trim(len(form_field))>
    -- ur cfquery insert / update etc wld be here
</CFIF>
+
have CFIF's for checking if it meets ur required criteria ... like range values ... or number formats ...
or if its text input - chk for certain characters that may not be allowed OR must be there for the text to be valid.

Such general checks that u may have - needs to be there in on a CFM page [on which the form is submitted] & once the checks are complete - then u cld do the insert/update or whatever action u need !

hth

K'Rgds
Anand
0
 
LVL 35

Assisted Solution

by:mrichmon
mrichmon earned 100 total points
ID: 10714633
If you look at a web page source you will not be able to see the server side checks.

As everyone has mentioned you should do both server side and client side validation, but I would like to add one thing.

A best practice that often does not get mentioned when doing error checking is that you should catch and display all error messages at once.

For example,  Let's say you left three fields blank (First Name, Telephone, and Birthday).  WOuld you as a user rather see:

Click Submit --> Error You forgot First Name
(you fix)
Click Submit --> Error You forgot Telephone
(you fix)
Click Submit --> Error You forgot Birthday
(you fix)
Click Submit --> It works

OR

CLick Submit --> Error You forgot Firstname, Telephone and Birthday
(you fix)
Click Submit --> It works

Most users prefer the second interface better as it shows them all the problems at once.  

CFFORM cannot do this for you.  And in fact will not necessarily check the fields in top down order so the first time it could show you an error at the top of the screen, then one at the bottom, then one at the top, then inthe middle, then the top again, etc.  You get the idea.  This is very frustrating to users.

So it is better to write your own validation so that you can check all of the fields at once and display the errors in order.

Here is how a sample page that submits to itself would look with both kinds of validation for an address :


<cfset ErrorMsg = "">
<cfset ErrorFlag = false>
<cfif isDefined("Form.SubmitForm")>
<cfif (Len(Form.FirstName) EQ 0)>
      <cfset ErrorMsg = ErrorMsg & "FirstName ">
</cfif>
<cfif (Len(Form.LastName) EQ 0)>
      <cfset ErrorMsg = ErrorMsg & "LastName ">
</cfif>
<cfif (Len(Form.Address1) EQ 0)>
      <cfset ErrorMsg = ErrorMsg & "Address1 ">
</cfif>
<!--- Do not need to check Address2 as it is optional --->
<cfif (Len(Form.City) EQ 0)>
      <cfset ErrorMsg = ErrorMsg & "City ">
</cfif>
<cfif Form.State EQ ""><!--- Make sure they selected an option from drop-down menu --->
      <cfset ErrorMsg = ErrorMsg & "State ">
</cfif>
<!--- Allow Zipcodes of the patterns 12345 or 12345-1234 --->
<cfif REFind("^\d{5}(-\d{4})?$", Form.Zip) EQ 0>
      <cfset ErrorMsg = ErrorMsg & "Zip ">
</cfif>
<cfset ErrorFlag = ErrorMsg NEQ "">
<cfif NOT ErrorFlag><!--- There were no errors --->
   <cflocation addtoken="no" url="newpage.cfm">
</cfif>
</cfif>

<html>
<head>
<title>Add Addresses</title>
<script type="text/javascript" language="JavaScript">
<!--
function validateForm()
{
var ErrMsg = "";
var ErrCount = 0;
if(document.AddressForm.FirstName.value == "")
{
      ErrCount++;
      ErrMsg += "Please enter a First Name.\n";
}
if(document.AddressForm.LastName.value == "")
{
      ErrCount++;
      ErrMsg += "Please enter a Last Name.\n";
}
if(document.AddressForm.Address1.value == "")
{
      ErrCount++;
      ErrMsg += "Please enter an address.\n";
}
if(document.AddressForm.City.value == "")
{
      ErrCount++;
      ErrMsg += "Please enter a City.\n";
}
if(document.AddressForm.State.value == "")
{
      ErrCount++;
      ErrMsg += "Please select a State.\n";
}
if(document.AddressForm.Zip.value == "" || document.AddressForm.Zip.length != 5 || document.AddressForm.Zip.length != 9)
{
      ErrCount++;
      ErrMsg += "Please enter a valid Zipcode.\n";
}
if(ErrCount == 1)
{
      alert("Please fix the following problem before continuing:\n" + ErrMsg);

      return false;
}
else if(ErrCount > 1)
{
      alert("Please fix the following problems before continuing:\n" + ErrMsg);
      return false;
}
else
{
      return true;
}
}
-->
</script>
</head>
<body>
<cfoutput>
<form name="AddressForm" method="post" action="AddAddress.cfm" onSubmit="return validateForm();">
<table border="0" cellpadding="1" cellspacing="1">
<tr>
      <td>* First Name :</td>
      <td><input type="text" name="FirstName" value="<cfif ErrorFlag>#Form.FirstName#</cfif>"></td>
      <td class="error_msg"><cfif Find("FirstName", ErrorMsg)>Please enter a first name for this address.<cfelse>&nbsp;</cfif></td>
</tr>
<tr>
      <td>* Last Name :</td>
      <td><input type="text" name="LastName" value="<cfif ErrorFlag>#Form.LastName#</cfif>"></td>
      <td class="error_msg"><cfif Find("LastName", ErrorMsg)>Please enter a last name for this address.<cfelse>&nbsp;</cfif></td>
</tr>
<tr>
      <td>* Address :</td>
      <td><input type="text" name="Address1" value="<cfif ErrorFlag>#Form.Address1#</cfif>"></td>
      <td class="error_msg"><cfif Find("Address1", ErrorMsg)>Please enter the street address.<cfelse>&nbsp;</cfif></td>
</tr>
<tr>
      <td>&nbsp;</td>
      <td><input type="text" name="Address2" value="<cfif ErrorFlag>#Form.Address2#</cfif>"></td>
      <td class="error_msg">&nbsp;</td>
</tr>
<tr>
      <td>* City :</td>
      <td><input type="text" name="City" value="<cfif ErrorFlag>#Form.City#</cfif>"></td>
      <td class="error_msg"><cfif Find("City", ErrorMsg)>Please enter the city for this address.<cfelse>&nbsp;</cfif></td>
</tr>
<tr>
      <td>* State :</td>
      <td>
            <cfif ErrorFlag><!--- set a flag so we know what value is default selected in drop down box --->
                  <cfset CurrentState = Form.State>
            <cfelse>
                  <cfset CurrentState = "">
            </cfif>
            <select name="State">
                  <option value=""></option>
                  <cfloop query="GetStates"><option value="#StateID#"<cfif ErrorFlag AND (StateID EQ Evaluate("Form.State"))> selected</cfif>>#StateName#</option></cfloop>
            </select>
      </td>
      <td class="error_msg"><cfif Find("State", ErrorMsg)>Please select the state for this address.<cfelse>&nbsp;</cfif></td>
</tr>
<tr>
      <td>* Zipcode :</td>
      <td><input type="text" name="Zip" value="<cfif ErrorFlag>#Form.Zip#</cfif>"></td>
      <td class="error_msg"><cfif Find("Zip", ErrorMsg)>Please enter the zipcode for this address.<cfelse>&nbsp;</cfif></td>
</tr>
<tr>
      <td align="center">
            <input type="submit" name="SubmitForm" value="Add New Address">
      </td>
      <td align="center">
            <input type="submit" name="Cancel" value="Cancel">
      </td>
      <td>&nbsp;</td>
</tr>
</table>
</form>
</cfoutput>

</body>
</html>
0
 
LVL 35

Expert Comment

by:mrichmon
ID: 10714691
WHoops - the one thing I forgot in the above was a query that I have called GetStates that pulls the list of available states from a DB to populate the dropdown menu.  I did that because I wanted you to see how to validate fields other than text.

Here is the query that should go at the top of the page :
<cfquery datasource="mydsn" name="GetStates">
      SELECT StateID, StateName FROM StateTable
</cfquery>

Also to validate checkboxes serverside you need to do :
<cfif IsDefined("Form.fieldname")>  If yes then the checkbox was marked.  If no then it was not.
For radio buttons you can test as above to see if none were selected.

If you don't want to use the IsDefined test then you can include a cfparam with a default value for checkboxes and radio buttons.

Hope that helps.
0
 
LVL 17

Expert Comment

by:Tacobell777
ID: 10717100
One easy way, and possibly the best path for you is to add _required to the field name, or add a hidden field with the same field anme + _required
example:

<input type="text" name="firstName_required">

OR

<input type="hidden" name="firstName_required">
<input type="text" name="firstName">

As I said before, but you happily ignored.
They only way to do validation is by using server-side, i.e. coldfusion and regular expression, if you do not use regular expressions than you are not really validating your input.
0
 

Author Comment

by:jeffmace
ID: 10723001
Thank you all for your answers.  I appreciate all the feedback that was given and I will implement some basic server side checks into my forms to assure that people will fill out all the required information.  

Thank you,
Jeff
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Periodically we have to update or add SSL certificates for customers. Depending upon your hosting plan you may be responsible for the installation and/or key generation. In the wake of Heartbleed many sites were forced to re-key. We will concen…
When it comes to showing a 404 error page to your visitors, you do not want that generic page to show, and you especially do not want your hosting provider’s ad error page to show either. In this article, I will show you how to enable the custom 40…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now