Reputation: 690
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?
Upvotes: 2
Views: 3350
Reputation: 1430
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>
Upvotes: 5
Reputation: 1605
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
Upvotes: 4
Reputation: 20794
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.
Upvotes: 1