Raymond Camden's Blog Rss

Ask a Jedi: Validating Numbers in a Flash Form Grid

Posted in ColdFusion | Posted on 10-24-2005 | 3,029 views

A reader asks:

If you have an updatable grid, how do you validate a field numeric before it is submitted?

This is one of those things that is pretty simple if you know ActionScript well. I don't, but have friends who do. Here is a simple example of it in action, and it can definitely be done better:

view plain print about
1<cfset data = queryNew("id,name,age")>
2
3<cfloop index="x" from="1" to="10">
4    <cfset queryAddRow(data)>
5    <cfset querySetCell(data,"id",x)>
6    <cfset querySetCell(data,"name","User #x#")>
7    <cfset querySetCell(data,"age",randRange(20,90))>
8</cfloop>
9
10
11<cfform format="flash" name="test" onSubmit="return checkNumbers()">
12    <cfformitem type="script">
13    function checkNumbers() {
14        for(var i=0; i < people.dataProvider.length; i++) {
15            var theValue = people.dataProvider[i].age;
16            if(isNaN(theValue)) {
17                outputarea.text = theValue + " is not a number.";
18                return false;
19            }
20        }
21        return true;
22
23    }
24    </cfformitem>
25    
26    <cfgrid name="people" query="data" selectMode="edit" />
27    <cfformitem type="text" id="outputarea" />
28    <cfinput type="submit" name="submit" value="Submit" />
29</cfform>

The beginning of the code simply creates a fake query for us to use. That query is passed to the cfgrid tag. Notice that I have turned on editing with selectMode="edit". To validate, I decided to use onSubmit. It may be possible to validate on change, but I had trouble getting it to work right. We use the new cfformitem type="script" to write a function that will check the values of our grid. I loop over every row in the grids dataProvider (just consider this the query behind the grid), and check the age column. (Technically I should check the ID as well.) I'm using isNaN which is short for "Is Not A Number" to check each value. If the value is bad, I write out an error and abort the form submission. You could even make this more intelligent and verify age is over 0, and below some sensible number like 130.

Comments

[Add Comment] [Subscribe to Comments]