%
'=======================================================================================================================
' FORMAT / PARSE HELPERS (generic, not tied to a table)
'=======================================================================================================================
' VBScript has no IIf; this evaluates both branches, so only use it with plain values.
Function Iif_(cond, whenTrue, whenFalse)
If cond Then Iif_ = whenTrue Else Iif_ = whenFalse
End Function
' True for a plain positive integer id (1-9 digits); use before trusting a route/form id.
Function Valid_Id(s)
Dim re : Set re = New RegExp
re.Pattern = "^[0-9]{1,9}$"
Valid_Id = re.Test(s & "")
End Function
' Date -> "mm/dd/yyyy" for display ("" for null / invalid).
Function Date_Fmt(d)
If IsNull(d) Or IsEmpty(d) Then
Date_Fmt = ""
ElseIf IsDate(d) Then
Date_Fmt = Right("0" & Month(d), 2) & "/" & Right("0" & Day(d), 2) & "/" & Year(d)
Else
Date_Fmt = ""
End If
End Function
' Date -> "yyyy-mm-dd" for HTML date inputs.
Function Date_Iso(d)
If IsNull(d) Or IsEmpty(d) Then
Date_Iso = ""
ElseIf IsDate(d) Then
Date_Iso = Year(d) & "-" & Right("0" & Month(d), 2) & "-" & Right("0" & Day(d), 2)
Else
Date_Iso = ""
End If
End Function
' "yyyy-mm-dd" (HTML date input) -> Date, or Null when blank/invalid.
Function Date_Parse(s)
Dim re, m, y, mo, d
Date_Parse = Null
Set re = New RegExp
re.Pattern = "^(\d{4})-(\d{2})-(\d{2})$"
If Not re.Test(s & "") Then Exit Function
Set m = re.Execute(s)(0)
y = CInt(m.SubMatches(0)) : mo = CInt(m.SubMatches(1)) : d = CInt(m.SubMatches(2))
If y < 2000 Or y > 2100 Or mo < 1 Or mo > 12 Or d < 1 Or d > 31 Then Exit Function
If Month(DateSerial(y, mo, d)) <> mo Then Exit Function
Date_Parse = DateSerial(y, mo, d)
End Function
' HTML-encodes text and turns line breaks into
.
Function Html_Nl2Br(s)
Html_Nl2Br = Replace(Replace(Replace(Server.HTMLEncode(s & ""), vbCrLf, "
"), vbLf, "
"), vbCr, "
")
End Function
' Quotes a value for CSV. Values that a spreadsheet would treat as a formula are prefixed with an apostrophe
' (CSV injection), except ordinary phone numbers like +1 (555) 123-4567.
Function Csv_Cell(v)
Dim s, first, re
If IsNull(v) Or IsEmpty(v) Then
Csv_Cell = ""
Exit Function
End If
s = CStr(v)
If Len(s) > 0 Then
first = Left(s, 1)
If first = "=" Or first = "@" Or first = vbTab Or first = vbCr Then
s = "'" & s
ElseIf first = "+" Or first = "-" Then
Set re = New RegExp
re.Pattern = "^[+\-][0-9 ().\-]*$"
If Not re.Test(s) Then s = "'" & s
End If
End If
If InStr(s, ",") > 0 Or InStr(s, """") > 0 Or InStr(s, vbCr) > 0 Or InStr(s, vbLf) > 0 Or Left(s, 1) = " " Or Right(s, 1) = " " Then
s = """" & Replace(s, """", """""") & """"
End If
Csv_Cell = s
End Function
%>