I have a variable to hold an id
Dim empId as String
So the format for a valid ID is:
'the first character should be a letter [A-Z]
'the rest of the string are digits e.g M2895 would be a valid id
I would like to check each of those characters to see if they fit the correct ID
So far, I have come across the isNumeric() function. Is there a similar function in VB.NET to check if a character is a string or alpha character?
You can use RegularExpressions instead of checking each character of your string by hand:
Dim empId as String = "M2895"
If Regex.IsMatch(empId, "^[A-Z]{1}[0-9]+$") Then
Console.WriteLine("Is valid ID")
End If
If you need a function isAlpha you can create this function by using RegularExpressions too:
Private Function isAlpha(ByVal letterChar As String) As Boolean
Return Regex.IsMatch(letterChar, "^[A-Z]{1}$")
End Function
For completion, to support estonian alphabet too, you can use the following:
Dim empId as String = "Š2859"
If Regex.IsMatch(empId, "^[^\W\d_]{1}[0-9]+$") Then
Console.WriteLine("Is valid ID")
End If
You can use functions which works for all Unicode characters
Char.IsLetter Method (String, Int32)
Indicates whether the character at the specified position in a specified string is categorized as a Unicode letter.
Char.IsDigit Method (Char)
Indicates whether the specified Unicode character is categorized as a decimal digit.
So you end up with validation like
Public Function IsValid(id As String)
If Char.IsLetter(id, 0) = False Then
Return False
End If
If id.Skip(1).All(Char.IsDigit) = False Then
Return False
End If
Return True
End Function
Here is my take an isAlpha function, answering the title of this question:
Public Shared Function isAlpha(ByVal s as String) as Boolean
if s is Nothing then return False
For Each c As Char in s
If not Char.IsLetter(c) then return False
Next
return True
End Function
However, to answer the body of the question, here is my mod of #Fabio's answer:
Public Function isMyAlphaCode(id As String) as Boolean
if id is Nothing then return False
if id.length < 2 then return False
If Char.IsLetter(id, 0) Then
Return False
End If
If id.Skip(1).All(Char.IsDigit) Then
Return False
End If
Return True
End Function
Related
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 have a vba function that checks if a user-input from a text box is positive integer or not. The code below:
Public Function IsPosInteger(n As Variant) As Boolean
If IsNumeric(n) = True Then
If (n = Int(n)) And n > 0 Then
IsPosInteger = True
Else
IsPosInteger = False
End If
Else
IsPosInteger = False
End If
End Function
The problem is that upon testing the function still returns false for a valid positive integer. Upon further investigation, I noticed that the variable type by default for texbox values is String. Probably the main reason why IsNumeric is returning false.
Function below is what I used to determine the type of the variable.
TypeName(n)
This worked for me.
I used an inputbox that contained:
strings (False)
negative numbers (False)
positive numbers (true)
positive numbers and letters (false)
Public Function IsPosInteger(n As Variant) As Boolean
If n > 0 And IsNumeric(n) Then IsPosInteger = True
End Function
Now, the other issue may arise that the value n is still technically type String due to the nature of the inputbox -- even if it passes the test of this function. If you wish to change this behavior, continue reading.
To do this, ensure that you are using ByRef (when this is intentional, I usually type out ByRef on the argument, even though it is automatically assumed by VBA that any argument passed to a function is ByRef if it doesn't explicitly state ByVal).
If this is the outcome you are wanting, then you can use this function:
Public Function IsPosInteger(ByRef n As Variant) As Boolean
If n > 0 And IsNumeric(n) Then
IsPosInteger = True
n = clng(n) '<-- This converts the variant (currently a string) n to type long,
' only if it passes the test
end if
End Function
You must ensure that n in the calling routine is of type Variant, else you will encounter an error.
Public Function IsPosInteger(s As String) As Boolean 'boolean data type is false by default.
If (IsNumeric(s) = False) Then Exit Function
If (s < 1) Then Exit Function
If (InStr(s, ".") = False) Then IsPosInteger = True
End Function
Function tests that the input is numeric, not less than 1, and does not contain a decimal. Here is an example of how you could use it in your calling sub:
Sub TestInput()
Dim sUserInput As String
Dim boolPositiveInt As Boolean
Dim i As Integer
sUserInput = Range("A1").Value2
boolPositiveInt = IsPosInteger(sUserInput)
If (boolPositiveInt = False) Then
MsgBox "Invalid input. Please enter a positive integer"
Exit Sub
End If
i = CInt(sUserInput)
'continue working with integer variable here
End Sub
I'm a total beginner in the VB language and I have a string in the format:
Smith, Alex (asmith#gmail.com)
I'm attempting to isolate "asmith" from this string. I'm assuming that we would have to split at the "(" and then at the "#" and obtain the 1st index?
Any help is appreciated.
I'm assuming that we would have to split at the "(" and then at the "#" and obtain the 1st index?
Your approach is correct. A literal translation of your algorithm to VB.NET would be:
Dim firstPartOfMailAddress = text.Split("("c)(1).Split("#"c)(0)
Explanation:
"("c is a character literal. Split expects a character, not a string (that would be "(").
Arrays are zero-based in VB.NET and indexed using the (...) operator. Thus, you take the second part (1) of the first split and the first part (0) of the second split.
Notes:
This code does not include any error handling and will fail horribly if the text does not contain the character (.
An alternative would be to extract the value using a regular expression, but if your are new to the language, splitting is a much easier option.
Here is an option for you:
Dim input = "Smith, Alex (asmith#gmail.com)"
Dim output= input.Split("("c, "#"c)(1)
use class :
Imports System.Globalization
Imports System.Text.RegularExpressions
Public Class RegexUtilities
Dim invalid As Boolean = False
Public Function IsValidEmail(strIn As String) As Boolean
invalid = False
If String.IsNullOrEmpty(strIn) Then Return False
' Use IdnMapping class to convert Unicode domain names.
Try
strIn = Regex.Replace(strIn, "(#)(.+)$", AddressOf Me.DomainMapper,
RegexOptions.None, TimeSpan.FromMilliseconds(200))
Catch e As RegexMatchTimeoutException
Return False
End Try
If invalid Then Return False
' Return true if strIn is in valid e-mail format.
Try
Return Regex.IsMatch(strIn,
"^(?("")("".+?(?<!\\)""#)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])#))" +
"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250))
Catch e As RegexMatchTimeoutException
Return False
End Try
End Function
Private Function DomainMapper(match As Match) As String
' IdnMapping class with default property values.
Dim idn As New IdnMapping()
Dim domainName As String = match.Groups(2).Value
Try
domainName = idn.GetAscii(domainName)
Catch e As ArgumentException
invalid = True
End Try
Return match.Groups(1).Value + domainName
End Function
End Class
and use code in form and customzition :
Dim util As New RegexUtilities()
Dim emailAddresses() As String = {"david.jones#proseware.com", "d.j#server1.proseware.com",
"jones#ms1.proseware.com", "j.#server1.proseware.com",
"j#proseware.com9", "js#internal#proseware.com",
"j_9#[129.126.118.1]", "j..s#proseware.com",
"js*#proseware.com", "js#proseware..com",
"js#proseware.com9", "j.s#server1.proseware.com",
"""j\""s\""""#proseware.com", "js#contoso.中国"}
For Each emailAddress As String In emailAddresses
If util.IsValidEmail(emailAddress) Then
Console.WriteLine("Valid: {0}", emailAddress)
Else
Console.WriteLine("Invalid: {0}", emailAddress)
End If
Next
I'm trying to validate a textbox. If user enters all lower case characters then convert it to all upper case. So when its added to the database its all upper case. I need help with my function, I don't know if its a syntax error or something, here it is. I'm using VB.Net 2010
Public Function CheckLetters(ByVal strIn As String) As Boolean
Dim i As Integer
Dim strOne As String
For i = 0 To Len(strIn) - 1
strOne = strIn.Substring(i, 1).ToUpper
Select Case strOne
Case "A" To "Z"
Case Else
Return False
End Select
Next
Return True
End Function
How 'bout this:
Return Regex.IsMatch(strIn, "^[a-z]*$")
or this
Return strIn.All(Function(c) Char.IsLower(c))
There's no good reason for this method to be anything other than a one-liner. But if you really want to loop through the characters:
For Each c As Char In strIn
If Not Char.IsLower(c) Then Return False
Next c
Return True
Your code runs just fine here (VB does not require the brackets after ToUpper, but it's good for readability) - it accepts a string and returns True if that string only contains the characters "A" through "Z", false otherwise. The function doesn't convert anything - just returns that Boolean result.
If you want to actually convert the string to upper case, just use .ToUpper() on the string itself, e.g.
Dim MyString As String = "Contains some text"
MyString = MyString.ToUpper()
' Above would set MyString to "CONTAINS SOME TEXT"
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