Search code examples
validationdatetimecoldfusioncoldfusion-2016

Checking for time


I have a form field which may have a date and may have a time in it. I need to confirm that both a date and time are present.

 <input type="text" name="transdate" ... />

I can use isDate(form.transdate) to check if there is a date, but it does not check if there is a time. I wish there was a isTime() function.

Addendum

The date time fields can be made to have

enter image description here

These fields are concatinated via

 date_cat = "#form.trans_date# #form.trans_date_h#:#form.trans_date_m# #form.trans_date_t#";

When I run this code:

cat: #date_cat# isValid(date): #isValid('date', date_cat)# isValid(time): #isValid('time', date_cat)#

I get

cat: 12/05/2018 :24 PM isValid(date): YES isValid(time): YES


Solution

  • Some people hate regular expressions. I love them. Why not just check the concatenated string?

    dtRegEx = "^(0[1-9]|1[0-2])/(0[1-9]|[1-2][0-9]|3[0-1])/[1-9][0-9]{3} (0[0-9]|1[0-2]):[0-5][0-9] (am|pm)$";
    
    if (reFind(dtRegEx, date_cat) and isDate(date_cat)) {
        // valid datetime
    } else {
        // invalid datetime
    }
    

    RegEx Breakdown

    ^
        string has to start with the whole pattern
    
    (0[1-9]|1[0-2])
        month in range from 01 to 09 or 10 to 12
    
    /
        date delimiter
    
    (0[1-9]|[1-2][0-9]|3[0-1])
        day in range from 01 to 09, 10 to 29 or 30 to 31
    
    /
        date delimiter
    
    [1-9][0-9]{3}
        year in range from 1000 to 9999
    
    space
        space, literally
    
    (0[0-9]|1[0-2])
        hour in range from 00 to 09 or 10 to 12
    
    :
        time delimiter
    
    [0-5][0-9]
        seconds in range from 00 to 59
    
    space
        space, again
    
    (am|pm)
        the meridiem stuff you guys from US and UK like so much :P
    
    $
        string has to end with the whole pattern
    

    Note that the above pattern could still have you end up with invalid day ranges like 02/31/2018, that's why you should still check with isDate().