Search This Blog

Tuesday, August 24, 2010

Validating a string with specific custom date format in VbScript

I have search for a vbscript function to meet my requirement of validating a date string with a specific date format but my badluck i am unable to find which meets my requirement.So i finally decide to write my own script to fulfill my requirement.
My custom function to validate / check for a custom date format in a date string it returns True or False
Assumptions:
Date format contains date in DD format, month in MM or MMM format, year in YY or YYYY format.
e.g. DD-MM-YYYY or MM-DD-YYYY or YY-DD-MM or MM-YY-DD or MM/YY/DD etc
If year is in YY then it consider it to be 2000 year only e.g. 10-15-02 and format is YY-DD-MM
then it will check for a valid date of 2010 15th Feb .





Function CheckDate(strDate,strFormat)
strFormat=UCase(strFormat)
If(Len(strDate)=Len(strFormat)) Then
Dim iStartD,iLastD,iStartM,iLastM,iStartY,iLastY,iFirstSeperator,iLastSeperator

iStartD=InStr(1,strFormat,"D")
iLastD=InStrRev(strFormat,"D")
iStartM=InStr(1,strFormat,"M")
iLastM=InStrRev(strFormat,"M")
iStartY=InStr(1,strFormat,"Y")
iLastY=InStrRev(strFormat,"Y")
For i=1 To Len(strFormat)
Dim x,seperators
seperators="/.-|:"
x=Mid(strFormat,i,1)
If(InStr(seperators,x)>0) Then
iFirstSeperator=InStr(strFormat,x)
iLastSeperator=InStrRev(strFormat,x)
Exit For
End if
Next
'WScript.Echo iFirstSeperator&" "&iLastSeperator

'WScript.Echo iStartD&" "&iLastD&" "&iStartM&" "&iLastM&" "&iStartY&" "&iLastY

Dim vDate,vMonth,vYear,validDate
validDate=False

If(iLastD>1) Then
vDate=Mid(strDate,iStartD,iLastD-iStartD+1)
Else
vDate="01"
End If
If(iLastM>1) Then
vMonth=Mid(strDate,iStartM,iLastM-iStartM+1)
Else
vMonth="01"
End If
If(iLastY>1) Then
vYear=Mid(strDate,iStartY,iLastY-iStartY+1)
Else
vYear="2010"
End If
If(Not Len(vYear)>2)Then
vYear="20"&vYear
End If
'WScript.Echo vDate &" "&vMonth&" "&vYear
If(Len(vMonth)>2) Then
WScript.Echo IsDate(vDate&"-"&vMonth&"-"&vYear)
If(IsDate(vDate&"-"&vMonth&"-"&vYear)) Then
WScript.Echo CDate(vDate&"-"&vMonth&"-"&vYear)
validDate=True
End If
ElseIf(Len(vMonth)<3) Then
WScript.Echo IsDate(vYear&"/"&vMonth&"/"&vDate)
If(IsDate(vYear&"/"&vMonth&"/"&vDate))Then
WScript.Echo CDate(vYear&"/"&vMonth&"/"&vDate)
validDate=True
End if
End If

If(iFirstSeperator>1 And validDate=True) Then
If(Mid(strFormat,iFirstSeperator,1)=Mid(strDate,iFirstSeperator,1) And Mid(strFormat,iLastSeperator,1)=Mid(strDate,iLastSeperator,1)) Then
validDate=True
Else
validDate=False
End If
End If

Else
validDate=False
End If


CheckDate=validDate
End Function