I am trying to validate email addresses to my vb.net windows form application,this is the validate email function written in another class
Public Function ValidateEmailAddress(strEmailAddress As String) As Boolean
Dim pattern As String
pattern = "^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$"
If Regex.IsMatch(strEmailAddress, pattern) Then
Return True
Else
Return False
End If
End Function
I then called the IsValid function from another class by writing this code
If ValidateEmailAddress(txtEmailAddress.Text) Then
MessageBox.Show("Email Valid")
Else
MessageBox.Show("Email Not Valid")
End If
On-Stepping throught this code,it skips past the Return True statement in the ValidateEmailAddress function an also skips the MessageBox.Show("Email Valid") in the isValid() function. therefore i get an Email not Valid return statement even wwhen i enter the correct email format. Please is the regex pattern correct or can anyone spot anything im doing wrong here. Thanks
For me it looks like a Regex problem. Try this one:
Public Function ValidateEmailAddress(strEmailAddress As String) As Boolean
Dim EmailRegex As New Regex("^([a-zA-Z0-9_\-\.\']+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$")
If EmailRegex.IsMatch(strEmailAddress) Then
Return True
Else
Return False
End If
End Function
Sorry for brief answer, at the moment I have very little time to point out where the error may be.
Related
Consider :
Private Function isAvailableQuantity() As Boolean
Try
sqL = "SELECT StocksOnHand FROM ITEM WHERE ItemNo = " & Val(txtSearch.Text) & ""
ConnDB()
cmd = New OleDbCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
If dr.Read = True Then
If Val(txtQuantity.Text) <= dr(0) Then
isAvailableQuantity = True
Else
MsgBox("Insuficient stocks", MsgBoxStyle.Critical, "Validate Stocks")
txtSearch.Clear()
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
cmd.Dispose()
conn.Close()
End Try
End Function
I don't know what to do. The older version visual studio doesn't get this error.
i am using vs 2022 right now and it seems to have an error on the contrary vs 2010 doesn't
In VB.NET, a Function is a method that returns a value and a Sub is a method that doesn't return a value. If your method doesn't need to return anything, use a Sub, e.g.
Private Sub DoSomething()
'Do some stuff here.
End Sub
If you do use a Function then there are two ways to return a value. The bad way is to assign a value to the implicit local variable that is named after the method, e.g.
Private Function DoSomething() As Boolean
'Do some stuff here.
DoSomething = True
End Function
That way basically only exists to support upgraded VB6 code. If your teacher is showing you that then they are obviously an old VB6 developer who hasn't actually learned VB.NET properly. The good way to return a value is with an explicit Return statement, e.g.
Private Function DoSomething() As Boolean
'Do some stuff here.
Return True
End Function
If there are multiple paths that execution could take through your code, you need to make sure that a value is returned on all of them. As an example, this code does not do that:
Private Function DoSomething() As Boolean
If Date.Now.DayOfWeek = DayOfWeek.Monday Then
Return True
End If
End Function
That will return True on Mondays but it doesn't return anything on other days. In this specific case, one fix would be this:
Private Function DoSomething() As Boolean
If Date.Now.DayOfWeek = DayOfWeek.Monday Then
Return True
End If
Return False
End Function
If you are going to use the bad way to return a value and you want to return a particular value on all but one code path then the logical thing to do is to set the return value at the start to the default and then only change it in that one place, e.g.
Private Function DoSomething() As Boolean
DoSomething = False
If Date.Now.DayOfWeek = DayOfWeek.Monday Then
DoSomething = True
End If
End Function
That last example is the easiest (although not best) fix for your scenario.
I have one vb.net code where the ID text box is checking if order ID is numeric only. Now my boss want me to change this with first letter and rest numbers like(A0000000) so he needs both ways full numeric and first letter and numeric.
my existing code is.
ElseIf (Not IsNumeric(txtworkorderID.Text)) Then
invalidWorkOrderNumber = True
how can i change this to check if all are numeric or alpha numeric?
I have little bit of programming knowledge.Can someone please help me?
You could use a function like if this is what you mean? Sorry bit trouble understanding what you fully want.
Function CheckForAlphaCharacters(ByVal StringToCheck As String)
If Not Char.IsLetter(StringToCheck.Chars(0)) Then
Return False 'first character is not a letter
End If
'other check if number
For i = 1 To StringToCheck.Length - 1
If Char.IsLetter(StringToCheck.Chars(0)) Then
Return False 'characters contain a letter
End If
next
Return True 'Return true if first character is a letter and rest number
End Function
Basically this will look at the string check to see if the first character is a letter, if it isn't return false, it will then check every character after the first to make sure its not a letter.
If Regex.IsMatch(number, "^[0-9 ]+$") Then
'This will see if the whole string is all numbers! so maybe mix both this and the on above to confirm either ways acceptable?
End If
You could do this with String.Substring to pull out each part and test it both ways. For instance, something like this:
Public Function ParseId(id As String) As ParsedId
Dim number As Integer
If id?.Length > 0 Then
If Integer.TryParse(id, number) Then
Return New ParsedId() With {
.Number = number }
End If
End If
If id?.Length > 1 Then
If Char.IsLetter(id(0)) And Integer.TryParse(id.Substring(1), number) Then
Return New ParsedId() With {
.Letter = id(0),
.Number = number }
End If
End If
Return Nothing
End Function
Public Class ParsedId
Public Property Letter As String
Public Property Number As Integer
End Class
But, if there's any chance that you are going to need to make it even more flexible in the future, you may want to consider using regex (which is shorter anyway):
Public Function ParseId(id As String) As ParsedId
Dim m As Match = Regex.Match(id, "^(?<Letter>[A-Z])?(?<Number>\d+)$")
If m.Success Then
Return New ParsedId With {
.Letter = m.Groups("Letter").Value,
.Number = Integer.Parse(m.Groups("Number").Value) }
Else
Return Nothing
End If
End Function
I know the statement String.IsNullOrEmpty which I use regulary.
But now I'm wondering if I could use something similar for Dictionaries
My Current Code:
Public Property ExpectedResults As Generic.Dictionary(Of String, String)
Public Function SomeMethod() As Boolean
'Some code
If (IsNothing(ExpectedResults)) Then
Return True
End If
If ExpectedResults.Count = 0 Then
Return True
End If
For Each key As String In ExpectedResults.Keys
'If Regex Matches value
Return True
'End If
Next
Return False
End Sub
Is it possible to replace those 2 Ifs with 1 single statement? Or am I searching for something that doesn't exist?
Thank you for your time.
If I understand correctly, You want to check if your Dictionary is NOT nothing and also contains items? In this case I would go with
If Not IsNothing(ExpectedResults) AndAlso ExpectedResults.Count > 0 Then
Return True
End If
The null-conditional operator makes it pretty tidy:
If ExpectedResults?.Count > 0 Then
Return True
End If
I put a try/catch block around some email sending logic. If the email succeeds, it gives a confirmation message, if it fails, it gives a failure message. Visual Studio is warning me that the function doesn't return a value on all code paths. Do I need to put return statements in each the Try and Catch blocks? If I do, for example put Return statements of False or Null at the end of the Try and Catch, will the other code preceding the Return statements still execute?
Function Sendmail(ByVal subject As String, ByVal msg As String, ByVal fromAddress As String, ByVal toAddress As String)
Try
Dim message As New MailMessage
message.From = New MailAddress(fromAddress)
For Each s As String In toAddress.Split(New [Char]() {";"c})
message.To.Add(New MailAddress(s))
Next
message.Subject = subject
message.Body = msg
message.IsBodyHtml = False
Dim client As New SmtpClient
client.Send(message)
pnlEmailSuccess.Visible = True
Catch ex As Exception
pnlEmailSuccess.Visible = False
pnlEmailError.Visible = True
lblErrorMsg.Text = ex.ToString
End Try
End Function
To answer your question, No you do not need a return statement in a Try/Catch. If you are not returning a value you don't need to write it in a function. Instead of a writing this in a function you could write it in a sub statement or a sub procedure. Here's a link to learn more about sub procedures.
VB.NET expects that the last statement executed in a function is a Return that will send a value back to the calling procedure. When the code encounters a Return statement, it immediately terminates execution of the code and returns the value specified, which is why it's usually the last statement in the function (see below for example). VB.NET is just warning you that there is a possibility (in your case, a certainty, as there's only one exit point from the function) that the function won't be returning a value. As another example of when this might happen, consider a function that has two different paths by which the code could exit:
Function IsThisFive(ByVal x as Integer) as Boolean
If x = 5 Then
Return True 'One code path exits here, with return value
Else
MsgBox("This is not five!")
End If
' Other code path exits here if x <> 5 -- no return value specified
End Function
To answer your question then, no, you don't need a return value inside both the Try and Catch blocks. You do, however, need one at the end of the block after End Try and before End Function. The code will run through Try..Catch..End Try construct, then Return a value.
If you don't need it to return a value, why not make it a sub rather than a function? A sub isn't expected to return a value, eliminating the problem. :-)
If you still wanted it to be a function, one common convention in programming is to only have a single exit point from a subroutine or function. This makes it easier to follow program flow when debugging or reading code.
You could do something like this:
Function SendMail(ByVal subject As String, ByVal msg As String, ByVal fromAddress As String, ByVal toAddress As String) as Boolean
Dim maiLSent as Boolean = False
Try
'send mail code
mailSent = True
Catch
'exception handling code here
mailSent = False
End Try
Return mailSent ' Only exit point from function is here
End Function
I added it to a timer with Try-Catch rather than continuously running. Worked perfectly.
I wrote this regex function
Public Function ValidateEmailAddress(ByVal txtEmailAddress As String) As Boolean
Dim pattern As String
pattern = "^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*#[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2,4})$"
If Regex.IsMatch(txtEmailAddress, pattern) Then
Return True
Else
Return False
End If
End Function
And on-calling the function in a sub procedure:
If ValidateEmailAddress(txtEmailAddress.Text) = True Then
Else
MessageBox.Show("Email Not Valid")
End If
Sub Procedure
When i enter the email, correctly or incorrectly i get the same message i.e email not valid,in addition to that on stepping through the code after the If statement it ignores the return true. Please can anyone spot what the issue is here?
As an alternative to BigYellowCactus's answer :- You can use something like this - I think this is preferable to using regex:
Public Shared Function IsValidEmailAddress(ByVal emailAddress As String) As Boolean
Try
Dim address As New MailAddress(emailAddress)
Return True
Catch ex As Exception
Return False
End Try
End Function
This will return False with #abc.com and bill# whereas just checking for # will return True