2

I need to write a function that can detect whether a string input is a valid format for a date. Allowable formats are:

#### (e.g. 2003)
##/#### (e.g. 12/2003)
#/#### (e.g. 9/2003)
##/####-##/#### (e.g. 12/2003-04/2005)

But I need to prevent invalid strings (e.g. "20031", "ABCD", "200A").

I've written a function to do this in VB already (below), but I need to do it in Javascript.

VB

Public Sub detectDateFormat(ByVal myDate As String)
    If myDate Like "####" Then
        'Do Stuff 1
    ElseIf myDate Like "##/####" Or myDate Like "#/####" Then
        'Do Stuff 2
    ElseIf myDate Like "##/####-##/####" Then
        'Do Stuff 3
    Else
        'Invalid date format
        Exit sub
    End If
End Function

It seems javascript has no equivalent to "Like", and it's tricky to detect if a character is a number or letter. Can anyone suggest a good way to do this?

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Urbycoz
  • 7,247
  • 20
  • 70
  • 108

1 Answers1

6

Closest you'll get is probably regular expressions. Much more powerful than LIKE but also can be more complicated.

For example:

If myDate Like "####" Then

Would be:

if (/^\d{4}$/.test(myDate)) { ... }
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Lloyd
  • 29,197
  • 4
  • 84
  • 98