One limitation of standard HTML forms is that you cannot validate that users input the type or range of data you expect. ColdFusion enables you to do several types of data validation by adding hidden fields to forms.
The following table describes the hidden field suffixes that you can use to do validation:
Note: Adding a validation rule to a field does not make it a required field. You need to add a separate _required hidden field if you want to ensure user entry.
The following procedure creates a simple form for entering a start date and a salary. It uses hidden fields to ensure that you enter data and that the data is in the right format.
This example illustrates another concept that might seem surprising. You can use the same ColdFusion page as both a form page and its action page. Because the only action is to display the values of the two variables that you enter, the action is on the same page as the form.
Using a single page for both the form and action provides the opportunity to show the use of the IsDefined function to check that data exists. This way, the form does not show any results until you submit the input.
<html>
<head>
<title>Simple Data Form</title>
</head>
<body>
<h2>Simple Data Form</h2>
<!--- Form part --->
<form action="datatest.cfm" method="Post">
<input type="hidden"
name="StartDate_required"
value="You must enter a start date.">
<input type="hidden"
name="StartDate_date"
value="Enter a valid date as the start date.">
<input type="hidden"
name="Salary_required"
value="You must enter a salary.">
<input type="hidden"
name="Salary_float"
value="The salary must be a number.">
Start Date:
<input type="text"
name="StartDate" size="16"
maxlength="16"><br>
Salary:
<input type="text"
name="Salary"
size="10"
maxlength="10"><br>
<input type="reset"
name="ResetForm"
value="Clear Form">
<input type="submit"
name="SubmitForm"
value="Insert Data">
</form>
<br>
<!--- Action part --->
<cfif isdefined("Form.StartDate")>
<cfoutput>
Start Date is: #DateFormat(Form.StartDate)#<br>
Salary is: #DollarFormat(Form.Salary)#
</cfoutput>
</cfif>
</html>
When the user submits the form, ColdFusion scans the form fields to find any validation rules you specified. The rules are then used to analyze the user's input. If any of the input rules are violated, ColdFusion sends an error message to the user that explains the problem. The user then must go back to the form, correct the problem, and resubmit the form. ColdFusion does not accept form submission until the user enters the entire form correctly.
Because numeric values often contain commas and dollar signs, these characters are automatically deleted from fields with _integer, _float, or _range rules before the form field is validated and the data is passed to the form's action page.
The following table describes the code and its function: