Reputation: 6110
I would like to validate date argument after user submits the form. My app is running on ColdFusion 9 and there is few built in functions like isDate()
but this function will return true even for some funky date values. I have approached this way to validate my date argument:
<cfarguments name="myDate" type="string" required="true">
<cfset getMonth = Month(myDate)>
<cfset getDay = Day(myDate)>
<cfset getYear = Year(myDate)>
<cfif getMonth LT 1 OR getMonth GT 12>
<cfset message = "Month value should be in a range between 1 and 12.">
<cfelseif getDay LT 1 OR getDay GT 31>
<cfset message = "Day value should be in a range btween 1 and 31.">
<cfelseif ((getMonth EQ 4 OR getMonth EQ 6 OR getMonth EQ 9 OR getMonth EQ 11) AND getDay EQ 31)>
<cfset message = "Month of April, June, September and November have 30 days.">
<cfelseif getMonth EQ 2>
<cfset isLeap = (getYear MOD 4 AND (getYear MOD 100 NEQ 0 OR getYear MOD 400 EQ 0))>
<cfif (getDay GT 29 OR (getDay EQ 29 AND NOT isLeap))>
<cfset message = "Only leap year can have 29 days.">
</cfif>
</cfif>
I'm wondering if this way to validate date has any issues? I tried to split the date to Day, Month and Year. Then I was checking each if it's in the right range. I'm not sure if there is anything else that I should be looking for. I'm using US Date Format mm/dd/yyyy in my app. If anyone have any suggestions please let me know. Thank you.
Upvotes: 1
Views: 733
Reputation: 20794
Here is something else you should be checking on the server side. This code:
writeoutput (dateformat("Apr 31", "yyyy-mm-dd"));
returns 1931-04-01. That's a perfectly valid date which passes every test in your question. What you do about it depends on whether or not the year 1931 is valid for your application.
Something else to consider is that if a value like "fred" is submitted, then your first command, <cfset getMonth = Month(myDate)>
, will throw an error. That sort of makes the rest of what you are attempting unnecessary.
Things you might consider are:
<cfinput mask="something">
in your form. Mind you, this option is annoyingPersonally I use a combination of instructions, pre-populating the inputs, <cfinput validate="date">
, and some custom tags I wrote several years ago that simply use isDate(). It's not perfect, but it gets the job done.
Upvotes: 1