2

How to check the date format using ColdFusion. I want to check that the user enters a date in the format yyyy-mm-dd. When a user enters a date in the format dd-mm-yyyy I want to show an error message. Is there any simple way to solve this?

Fish Below the Ice
  • 1,273
  • 13
  • 23
Sathish Chelladurai
  • 670
  • 1
  • 8
  • 23

3 Answers3

5

Do you need to validate the date format from the server side? Here I've given a simple RegEx check to check the format and did some checks to validate.

<cfset regex = '[0-2][0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9]'>
<cfset myDate = '2006-12-39'>
<cfset MatchedDate = REMatchNoCase(regex, myDate)>
<cfif arrayLen(MatchedDate) AND isDate(myDate) AND MatchedDate[1] EQ myDate>
    Valid date
<cfelse>
    Invalid date
</cfif>
Marikkani Chelladurai
  • 1,430
  • 1
  • 13
  • 23
4

As I said in comment, you can validate it on client side with following function

function validateDate(){

var dt = document.forms["Form_Name"]["Date_Field"].value;
var pattern =/^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})$/;
if (dt == null || dt == "" || !pattern.test(dt))
{
    alert("invalid date");
    return false;
}
else{
    return true
}

}

then in cf code, while processing

<cfset desiredFormat=DateFormat(form.Date_Field,"yyyy-mm-dd")>

ps: the js function was taken from Javascript Date Validation ( DD/MM/YYYY) & Age Checking

Community
  • 1
  • 1
CFML_Developer
  • 1,565
  • 7
  • 18
1

You could do this:

<cfinput name="StartDate" 
validate="date" 
type="text" 
maxlength="10" 
mask="9999-99-99"
message="Start Date must be a valid date." 
required="yes">

The key is the mask attribute. However, if you pre-populate this field, attempting to change the value can become frustrating.

Dan Bracuk
  • 20,699
  • 4
  • 26
  • 43
  • I would recommend the [jquery masked input plugin](http://digitalbush.com/projects/masked-input-plugin/) before using `cfinput`. stay away from the CFUI stuff. – Sean Coyne Jul 18 '14 at 18:30