函數程式碼
Function IsInteger(para)
On Error Resume Next
Dim str, l, i
If IsNull(para) Then IsInteger = False: Exit Function
str = CStr(para)
If Trim(str) = "" Then IsInteger = False: Exit Function
l = Len(str)
For i = 1 To l
If Mid(str, i, 1) > "9" Or Mid(str, i, 1) < "0" Then
IsInteger = False
Exit Function
End If
Next
IsInteger = True
If Err.Number <> 0 Then Err.Clear
End Function
使用範例
<%
Response.Write IsInteger("123") & "
" ' True
Response.Write IsInteger("-123") & "
" ' False (負號非數字)
Response.Write IsInteger("12.3") & "
" ' False
Response.Write IsInteger("") & "
" ' False
Response.Write IsInteger(Null) & "
" ' False
%>
改進版:支援負號與正則
Function IsInteger2(val)
Dim re : Set re = New RegExp
re.Pattern = "^-?\d+$"
IsInteger2 = re.Test(CStr(val))
End Function
注意
- 原函數不支援負整數,若需支援請加入首字元檢查
-。
- 大數值超出 VBScript 整數範圍 (-2,147,483,648 ~ 2,147,483,647) 仍回傳 True,實際轉型會溢位。
- 參數化查詢才是根本防禦,型別檢查僅為輔助。