Server side validating fields
As many of us know by now, it is never best to only validate fields with client side code. You must also validate on the server.
As I was writing code today for a multi-page form, I was trying to think of the best way to validate fields. Although the below is verbose and written in ColdFusion, it can be easily ported to any other language that supports arrays, lists, or hashes – and it can be placed in one line if your language supports associative arrays.
Required fields
For this one I used:
<cfset requiredFields = StructNew()>
<cfset requiredFields['name'] = 'Name'>
<cfset requiredFields['email'] = 'Email address'>
<cfset requiredFields['message'] = 'Message'>
<cfloop collection="#requiredFields#" item="i">
<cfif NOT StructKeyExists(form, i) OR form[i] EQ ''>
<cfset session.errors[i] = 'Field <strong>"' & requiredFields[i] & '"</strong> cannot
be empty.'>
</cfif>
</cfloop>
In this case, the form variable is the name of the form field itself :
requiredFields['email'] = <input type="text" name="email" />
The value of that field is a more friendly name to display with the error messages.
Field Name cannot be empty.
The same type of structures are then setup for numbers, dates, emails, and whatever else may need to be validated. Each loop entry is added to the session.errors array to maintain the errors and then cleared upon re-calling the validation page.
The sessions array is displayed with:
<cfif NOT StructIsEmpty(session.errors)>
<style type="text/css">
li{margin-left:10px}
</style>
<ul class="errorBox">
<cfloop collection="#session.errors#" item="i">
<cfoutput><li>#session.errors[i]#</li></cfoutput>
</cfloop>
</ul>
</cfif>
Creating a list displaying the errors.
**Additionally, to make it an even better experience, you can add an error highlight color to the row that caused the error. For example:
<td style="background-color:<cfif StructKeyExists(session.errors, 'name')>errorRow"><input type="text" name="name" /></td>
** If all of your fields are required, you can simply loop over the form fields and popuplate your errors array… but you may not have the friendly names.
So, why should you validate with server side code?
While client side code such as Javascript makes the user experience much more enjoyable, there are several reasons to also validate on the server.
- Checking on the server can be more verbose and accurate, especially if you need to check against a query (although AJAX would do this as well)
- Javascript can easily be turned off
- YOUR Javascript code can be hacked since it is visible there on the page.
- Your page can be copied completely, javascript removed, and submitted to the server.
- Your Javascript may not work across all browsers and mobile devices.
- Some coders make code inaccessible when they do not make sure the code works without Javascript
So why should you even use it?
- It prevents a trip to the server
- Your users will love you since things will work faster
- You can do muchos with AJAX
Filed under: Beginner, ColdFusion, PHP | Leave a Comment
Simple JQuery check-all
Simple check all with Jquery:
function checkAll(el, fieldName){
var checkBoxes = $('input[name=' + fieldName + ']');
var curValue = el.value;
if(curValue == 'Check All'){
$.each(checkBoxes, function() {this.checked = true});
el.value = 'Uncheck All';
} else {
$.each(checkBoxes, function() {this.checked = false});
el.value = 'Check All';
}
}
How to use?
Pass in the “this” keyword as the first parameter. Second, pass in the name of the fields that contain the checkboxes. This works only if you set your check all button’s value to ‘Check All’ (ways around this of course).
What’s going on?
Jquery gets all of the elements on the page that are input and have the name attribute equal to the name you passed in. The if conditional checks to see if the value of the first parameter is equal to ‘Check All’. If it is, we iterate over each checkbox and set it to true. We then change the value to ‘uncheck all’. If the value of the first parameter is equal to ‘uncheck all’ we set each checkbox to false, and reset the value to ‘check all’.
Filed under: Beginner, Javascript, Jquery | Leave a Comment
Creating a javascript select box with numbered selections in multiples:
var i;
var totalRows = 20;
var selectBox = document.getElementById('thisSelect');
for (i = 1; i < = totalRows; i++ ){
if( (i % 5) == false ){
var newOption = new Option(i, i);
selectBox.options.add(newOption);
}
}
What's going on?
Initialize variables:
var i;
var totalRows = 20;
var selectBox = document.getElementById('thisSelect');
var newOption;
Loop over total rows:
for (i = 1; i <= totalRows; i++ ){
...
}
Check if the current number divided by five returns 0 (loosely false).
if( (i % 5) == false){
...
}
If so, add new option. Then add to selectbox:
newOption = new Option(i, i); selectBox.options.add(newOption);
*Alternatively use the DOM when creating the option by using CreateElement.
Result
5
10
15
20
How to add "all" selection?
newOption = new Option('All [' + totalRows + ']', totalRows);
selectBox.options.add(newOption);
Final result
All
5
10
15
20
Filed under: Beginner, Javascript | Leave a Comment
Today while working with a ColdFusion component and attempting to create a constructor name init, I came across the below error :
The value returned from function init() is not of type manager.
If the component name is specified as a return type, the reason for this error might be that a definition file for such component cannot be found or is not accessible.
Doing a search online yielded unhelpful (at least in my situation) results. I was completely confused as to why my init constructor function would work on other cfc’s, but not on this one. My init function was simple:
<cffunction name="init" access="public" returntype="manager">
<cfargument name="dsn" type="string" required="yes">
<cfset this.dsn = arguments.dsn>
<cfreturn this>
</cffunction>
And my component:
<cfcomponent hint="manager">
But… Since ColdFusion is Java based, if I wanted to do this I would need to make sure that not only should my init function return this, and the returntype be the same name as the component hint, but the page needed to be named the same as those two as well.
And yes! After all of that, the init function worked as expected.
Filed under: ColdFusion | 1 Comment
I am a programmer. However, I am also a lover of any language – be it computers, foreign, or even my own. Therefore, I like to read, I love to learn, and I love to understand. One of the areas in my life that this applies to is creating beautiful code. And of course, as important as the code itself lies the commenting of the code. What happens years from now when you quit your job, someone else comes in, and they cannot understand the purpose of a certain parameter, argument, or function ? Or worse, what happens when two weeks from now you cannot understand the reason why a certain block of code is there OR what the function of it really is? Alas, the code has to be re-written, or taken a part piece by piece and possibly renamed.
Of course, naming variables and function names properly will help with much of the distress, however comments created in plain English helps a lot as well.
Many of the reasons I comment the way that I do comes from the PEAR coding standards for header comment blocks. I have also been to numerous web pages, and read many different books about programming. Lots of people have different ways of doing this, but this is my preference. I would be interested in hearing what you do OR what you would change about my commenting philosophies.
General places I add multi-line comments:
- Top of all pages
- Top of include files
- Top of javascript and CSS files
- Beginning of loops
General places I add single-line comments:
- End of loop – inline comment
This is not to say that comments should always be in these places. Use comments with some common sense! Place comments at the beginning of long blocks, not on every line of your code. Make your page easy to understand, not overly complicated due to trying to make it understandable. Comment code where the reason for the block of code is not instantly clear. Finally, if you are already using good naming practices for your functions and variables, your code should be pretty understandable with one good definition.
Comments that I usually add:
- Description* : If describing a function, it should describe why the function works, and not how. The how is visible, but the reason as to why you did it is not. What was your reason for this function? Are there any reasons that you did it this way? Is there a gotcha you found along the way when developing, and that is why you created it like this? Did it take you a while to figure this out? Is this a cross-reference to somewhere else? Did you *borrow* some of this code from somewhere? Is there somewhere that explains why you did what you did a certain way?
Which is better:- Loops over the iterator variable fifty times and adds the value to the array.
- Creates colors array to be used with the animals class.
- Creator*
- Date created*
- What is returned and returned data type
- Any parameters, parameter data type, and short definition if necessary
- Page calling (if include)
- Dependencies
- TODO
- Change log (only for major changes (example below is not major!))
- Change date
- Change by initials
- Change description
*always included
Javascript example:
/** * Validates a string * Author : CodeStar * Called from: index.php * @return boolean * @param string myString:: String entered into input field * @todo :: remove un-needed variable * Changelog: * 10/10/2008 C.S. :: Renamed inner loop from 'i' to 'valIndex' */
A few comment tags:
- HTML: <!– comment text –>
- CSS: /* comment text */
- C#, C++, CFScript, Javascript & PHP: //for single || /* multi-line comment */ for multiple
- CFML : <!— multi-line comment —>
- SQL server: — (two dashes) for single || /* multi-line comment */ for multiple
- MySQL: — (two dashes) OR # for single || /* multi-line comment */ for multiple
- Pear, .htaccess : #
*Final tip* – Comment as you go or at the beginning. Don’t wait until the very end… you may not do it, forget about it, and then later have problems!
Filed under: Beginner | Leave a Comment
Ever have a textbox where a person needs to enter a number, and they enter something like… $24.56? Or even 45,898.68? I have. The worst is that I wasn’t working on a database I created, and I further needed the dollar entered to be a whole number – without changing a lot of stuff =). I could have used money or decimal, but the way things were written – that was not an option. A javascript check would also work – but it of course wouldn’t work if turned off. So, off to create a utility function I go!
This can be changed over to CFScript, PHP, or really any other language. For PHP, change the RE* functions to the preg_* functions, for ‘ceiling’ change to ceil, and for ‘val’ change to floatval or intval.
NOTE:
- This is not multi-line compatible but can be change by adding the \m pattern modifier if your language allows it.
- If you do want to allow decimals (if you are using decimal, float, or money format in your database), remove the ceiling function, and the period.
- I used brackets in my regular expression instead of the alternation character so I could add/remove as needed based on locale.
- I did not need to check for negative numbers, so this is purely based on positive numbers but can still be modified to allow negatives by adjusting the regular expression check.
Steps taken:
- Create a function that takes an argument. In this case the argument I am accepting is a string and it is required. My variable name is ‘thisNumber’.
- <cffunction name="DollarToWhole" access="public" returntype="numeric" hint="Removes symbols from dollar, rounds up, and returns integer">
</cffunction>
- <cffunction name="DollarToWhole" access="public" returntype="numeric" hint="Removes symbols from dollar, rounds up, and returns integer">
- Setup the regular expression checks. isDollarFormat checks that the submitted string is indeed a dollar format. It can include any of the following: dollar sign ($), comma (,), period (.), or and number (\d). It does not HAVE to have anything, but it can have as many of these items as needed (
*). DollarChars are the common characters that could be entered as a number (dollar sign, comma).- <cfset var isDollarFormat = '^[$,.\d]*$'>
- <cfset var dollarChars = '[$,]'>
- Remove the parts from DollarChars that I want to be removed ( dollar sign and comma). Since I am rounding up, I do not want to remove the period; I want it to remain a decimal until I get to the end.
- <!—Remove dollars and commas —>
<cfset thisNumber = REReplace(thisNumber,dollarChars, '', 'all')>
- <!—Remove dollars and commas —>
- Check to make sure that my entered dollar amount (thisNumber) is a valid dollar number to my specifications in step 2. If not I attempt to get any numbers that are in the beginning of the string entered, if there are no numbers I will make thisNumber zero. (Set this however you want – or throw an error)
- <!—Check that this is a correct dollar format —>
<cfif REFind(isDollarFormat,thisNumber) EQ 0><cfset thisNumber = Val(thisNumber)> </cfif>
- <!—Check that this is a correct dollar format —>
- Round the number up to a valid whole number.
- <!—Round current number up to full dollar —>
<cfset thisNumber =Ceiling(thisNumber)>
- <!—Round current number up to full dollar —>
- Return thisNumber – my whole number without any dollars or commas ready to go into the database!
- <cfreturn thisNumber>
symbols from dollar, rounds up, and returns integer">
<cfargument name="thisNumber" type="string" required="yes">
<cfset var isDollarFormat = '^[$,.\d]*$'>
<cfset var dollarChars = '[$,]'>
<!— Remove dollars and commas —>
<cfset thisNumber = REReplace(thisNumber, dollarChars, '', 'all')>
<!— Check that this is a correct dollar format —>
<cfif REFind(isDollarFormat, thisNumber) EQ 0>
<cfset thisNumber = Val(thisNumber)>
</cfif>
<!— Round current number up to full dollar —>
<cfset thisNumber = Ceiling(thisNumber)>
<cfreturn thisNumber>
</cffunction>
Examples:
UNFORMATTED :: $36,000.54
FORMATTED :: 36001
UNFORMATTED :: NA
FORMATTED :: 0
UNFORMATTED :: 32.36 I Think
FORMATTED :: 33
Filed under: ColdFusion, Intermediate, PHP, Regular expressions | Leave a Comment
Domain after URL
One of the sites that I frequent daily has an interesting take on URL’s. It is both something that I have grown to love and appreciate. After the end of each link, the domain that the link refers to is clearly printed. Why is this useful? Well, comments on a site or posts on a message board are open to links from many a user; adding the domain name after the URL helps to ensure the safety of your users, and helps them know exactly what to expect. Everyone doesn’t know to look at the link in the status bar before clicking – and this just takes one extra step out of it (plus it is simple to add).
An example:
This is a test string with http://mycoolsite.com and who knows in it.
These are definitely not the correct URLs. But what if it were like this:
This is a test string with http://mycoolsite.com [yahoo.com] and who knows [google.com] in it.
This obviously helps with identifying the URL, without having to click on it or hover over it.
With that said…. let’s get down to business.
First, build the string that will have the information that contains the URL(s).
$string = 'This is a test string with <a href="http://yahoo.com/" title="test">http://coolsite.com</a> and <a href="http://google.com">who knows</a> in it.';
Next we will use preg_replace_callback. With this built-in PHP function we will use a regular expression to find a URL in our string. The regular expression looks for everything between an anchor tag but will only use the actual URL that the anchor text is linked to. We will then create a callback function that will take the matches from our string, grab the domain using parse_url, and return it back to the string.
function addDomain($matches)
{
$thisUrl = parse_url($matches[1]);
$output = $matches[0] . ' <span class="addHost">[' . $thisUrl['host'] . ']</span>';
return $output;
}
$newString = preg_replace_callback('|<a .*?href="(http://.*?)/?".*?>(.*?)</a>|', "addDomain", $string);
All together we have (with a class added for styling):
$string = 'This is a test string with <a href="http://yahoo.com/" title="test">http://coolsite.com</a> and <a href="http://google.com">who knows</a> in it.';
/**
* Returns string with domain name after any entered URL. Actual url in anchor is used to prevent basic URL spoofing
*
* @param array $matches - matches found in preg_replace_callback function
* @return string - returns URL with previous entry and domain in brackets. Styled using class "addHost".
*/
function addDomain($matches)
{
$thisUrl = parse_url($matches[1]);
$output = $matches[0] . ' <span class="addHost">[' . $thisUrl['host'] . ']</span>';
return $output;
}
$newString = preg_replace_callback('|<a .*?href="(http://.*?)/?".*?>(.*?)</a>|', "addDomain", $string);
Filed under: Intermediate, PHP, Usability | Leave a Comment
Search
-
Blogroll
Directories
Websites
Recent Entries
Categories
- Beginner (4)
- ColdFusion (3)
- Intermediate (2)
- Javascript (2)
- Jquery (1)
- PHP (3)
- Regular expressions (1)
- Usability (1)