Custom Form Validation - Exercise

Contact Us or call 1-877-932-8228
Custom Form Validation - Exercise

Custom Form Validation

Duration: 20 to 30 minutes.
  1. Open FormValidation/Exercises/AddEntry.cfm in your editor.
  2. Add the following validation.
    • Time format should be "##:##".
    • Comments should be required and not longer than 50 characters.
  3. Open AddEntry.cfm in your browser to test your new page.
  1. The date entered should be in the past. You can use the DateCompare() function to compare it to the current time. If the date has not yet occurred, return an error.
  2. Using your other knowledge of ColdFusion, let the user know how fast she was running.

Solution:

FormValidation/Solutions/AddEntry.cfm
---- C O D E   O M I T T E D ----
<cfif ListLen(FORM.time,":") NEQ 2>
		<cfset errors = "#errors#<li>The time must be in the format <i>MM:SS</i>.</li>">
		<cfset timeclass="errors">
	<cfelse>
		<cfset minutes = ListGetAt(FORM.time,1,":")>
		<cfset seconds = ListGetAt(FORM.time,2,":")>
		<cfif NOT isNumeric(minutes) OR NOT isNumeric(seconds) OR Len(minutes) GT 2 OR Len(seconds) GT 2>
			<cfset errors = "#errors#<li>The time must be in the format <i>MM:SS</i>.</li>">
			<cfset timeclass="errors">
		</cfif>
	</cfif>
	
	<cfif Len(Trim(FORM.comments)) EQ 0 OR Len(Trim(FORM.comments)) GT 50>
		<cfset errors = "#errors#<li>You must include a comment of up to 50 characters.</li>">
		<cfset commentsclass="errors">
	</cfif>
---- C O D E   O M I T T E D ----

Challenge Solution:

FormValidation/Solutions/AddEntry-challenge.cfm
---- C O D E   O M I T T E D ----
<cfif isDefined("FORM.submitted")>
	<cfif NOT isDate(FORM.date)>
		<cfset errors = errors & "<li>The date is invalid.</li>">
		<cfset dateclass="errors">
	<cfelseif DateCompare(Now(),FORM.date) EQ -1>
		<cfset errors = errors & "<li>The date must be in the past.</li>">
		<cfset dateclass="errors">
	</cfif>
---- C O D E   O M I T T E D ----
		<!---Calculate Speed--->
		<cfset totalhours = (minutes + (seconds/60))/60>
		<cfset speed = intDistance/totalhours>
		<cfoutput>
		<br>You were running at an average speed of #speed# #units# per hour.
		</cfoutput>
---- C O D E   O M I T T E D ----

Next