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"
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 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
In an MS Access 2007 project report, I have the following (redacted) query:
SELECT SomeCol FROM SomeTable
The problem is, that SomeCol apparently contains some invisible characters. For example, I see one result returned as 123456 but SELECT LEN(SomeCol) returns 7. When I copy the result to Notepad++, it shows as ?123456.
The column is set to TEXT. I have no control over this data type, so I can't change it.
How can I modify my SELECT query to strip out anything non-numeric. I suspect RegEx is the way to go... alternatively, is there a CAST or CONVERT function?
You mentioned using a regular expression for this. It is true that Access' db engine doesn't support regular expressions directly. However, it seems you are willing to use a VBA user-defined function in your query ... and a UDF can use a regular expression approach. That approach should be simple, easy, and faster performing than iterating through each character of the input string and storing only those characters you want to keep in a new output string.
Public Function OnlyDigits(ByVal pInput As String) As String
Static objRegExp As Object
If objRegExp Is Nothing Then
Set objRegExp = CreateObject("VBScript.RegExp")
With objRegExp
.Global = True
.Pattern = "[^\d]"
End With
End If
OnlyDigits = objRegExp.Replace(pInput, vbNullString)
End Function
Here is an example of that function in the Immediate window with "x" characters as proxies for your invisible characters. (Any characters not included in the "digits" character class will be discarded.)
? OnlyDigits("x1x23x")
123
If that is the output you want, just use the function in your query.
SELECT OnlyDigits(SomeCol) FROM SomeTable;
There is no RegEx in Access, at least not in SQL. If you venture to VBA, you might as well use a custom StripNonNumeric VBA function in the SQL statement.
e.g. SELECT StripNonNumeric(SomeCol) as SomeCol from SomeTable
Function StripNonNumeric(str)
keep = "0123456789"
outstr = ""
For i = 1 to len(str)
strChar = mid(str,i,1)
If instr(keep,strChar) Then
outstr = outstr & strChar
End If
Next
StripNonNumeric = outstr
End Function
You can do it all in a query, combining this question with your previous question, you get:
SELECT IIf(IsNumeric([atext]),
IIf(Len([atext])<4,Format([atext],"000"),
Replace(Format(Val([atext]),"#,###"),",",".")),
IIf(Len(Mid([atext],2))<4,Format(Mid([atext],2),"000"),
Replace(Format(Val(Mid([atext],2)),"#,###"),",","."))) AS FmtNumber
FROM Table AS t;
Public Function fExtractNumeric(strInput) As String
' Returns the numeric characters within a string in
' sequence in which they are found within the string
Dim strResult As String, strCh As String
Dim intI As Integer
If Not IsNull(strInput) Then
For intI = 1 To Len(strInput)
strCh = Mid(strInput, intI, 1)
Select Case strCh
Case "0" To "9"
strResult = strResult & strCh
Case Else
End Select
Next intI
End If
fExtractNumeric = strResult
End Function
I'm wondering how I can check if a string contains either "value1" or "value2"?
I tried this:
If strMyString.Contains("Something") Then
End if
This works, but this doesn't:
If strMyString.Contains("Something") or ("Something2") Then
End if
This gives me the error that conversion from string to Long can't be done.
If I put the or ("Something2") inside the parenthesis of the first one, it gives me the error that the string cannot be converted to Boolean.
So how can I check if the string contains either "string1" or "string2" without having to write too much code?
You have to do it like this:
If strMyString.Contains("Something") OrElse strMyString.Contains("Something2") Then
'[Put Code Here]
End if
You need this
If strMyString.Contains("Something") or strMyString.Contains("Something2") Then
'Code
End if
In addition to the answers already given it will be quicker if you use OrElse instead of Or because the second test is short circuited. This is especially true if you know that one string is more likely than the other in which case place this first:
If strMyString.Contains("Most Likely To Find") OrElse strMyString.Contains("Less Likely to Find") Then
'Code
End if
Here is the alternative solution to check whether a particular string contains some predefined string. It uses IndexOf Function:
'this is your string
Dim strMyString As String = "aaSomethingbb"
'if your string contains these strings
Dim TargetString1 As String = "Something"
Dim TargetString2 As String = "Something2"
If strMyString.IndexOf(TargetString1) <> -1 Or strMyString.IndexOf(TargetString2) <> -1 Then
End If
NOTE: This solution has been tested with Visual Studio 2010.
You have ("Something2") by itself - you need to test it so a boolean is returned:
If strMyString.Contains("Something") or strMyString.Contains("Something2") Then
If strMyString.Contains("Something") or strMyString.Contains("Something2") Then
End if
The error indicates that the compiler thinks you want to do a bitwise OR on a Boolean and a string. Which of course won't work.
If strMyString.Tostring.Contains("Something") or strMyString.Tostring.Contains("Something2") Then
End if
I've approached this in a different way. I've created a function which simply returns true or false..
Usage:
If FieldContains("A;B;C",MyFieldVariable,True|False) then
.. Do Something
End If
Public Function FieldContains(Searchfor As String, SearchField As String, AllowNulls As Boolean) As Boolean
If AllowNulls And Len(SearchField) = 0 Then Return True
For Each strSearchFor As String In Searchfor.Split(";")
If UCase(SearchField) = UCase(strSearchFor) Then
Return True
End If
Next
Return False
End Function
If you want to disregard whether the text is uppercase or lowercase, use this:
If strMyString.ToUpper.Contains("TEXT1") OrElse strMyString.ToUpper.Contains("TEXT2") Then
'Something
End if
Interestingly, this solution can break, but a workaround:
Looking for my database called KeyWorks.accdb which must exist:
Run this:
Dim strDataPath As String = GetSetting("KeyWorks", "dataPath", "01", "") 'get from registry
If Not strDataPath.Contains("KeyWorks.accdb") Then....etc.
If my database is named KeyWorksBB.accdb, the If statement will find this acceptable and exit the If statement because it did indeed find KeyWorks and accdb.
If I surround the If statement qualifier with single quotes like 'KeyWorks.accdb', it now looks for all the consecutive characters in order and would enter the If block because it did not match.
Hopefully this should be an easy question. In Java I think it's compareTo().
How do I compare two string variables to determine if they are the same?
ie:
If (string1 = string2 And string3 = string4) Then
'perform operation
Else
'perform another operation
End If
I would suggest using the String.Compare method. Using that method you can also control whether to have it perform case-sensitive comparisons or not.
Sample:
Dim str1 As String = "String one"
Dim str2 As String = str1
Dim str3 As String = "String three"
Dim str4 As String = str3
If String.Compare(str1, str2) = 0 And String.Compare(str3, str4) = 0 Then
MessageBox.Show("str1 = str2 And str3 = str4")
Else
MessageBox.Show("Else")
End If
Edit: If you want to perform a case-insensitive search you can use the StringComparison parameter:
If String.Compare(str1, str2, StringComparison.InvariantCultureIgnoreCase) = 0 And String.Compare(str3, str4, StringComparison.InvariantCultureIgnoreCase) = 0 Then
In vb.net you can actually compare strings with =. Even though String is a reference type, in vb.net = on String has been redefined to do a case-sensitive comparison of contents of the two strings.
You can test this with the following code. Note that I have taken one of the values from user input to ensure that the compiler cannot use the same reference for the two variables like the Java compiler would if variables were defined from the same string Literal. Run the program, type "This" and press <Enter>.
Sub Main()
Dim a As String = New String("This")
Dim b As String
b = Console.ReadLine()
If a = b Then
Console.WriteLine("They are equal")
Else
Console.WriteLine("Not equal")
End If
Console.ReadLine()
End Sub
Dim MyString As String = "Hello World"
Dim YourString As String = "Hello World"
Console.WriteLine(String.Equals(MyString, YourString))
returns a bool True. This comparison is case-sensitive.
So in your example,
if String.Equals(string1, string2) and String.Equals(string3, string4) then
' do something
else
' do something else
end if
I know this has been answered, but in VB.net above 2013 (the lowest I've personally used) you can just compare strings with an = operator. This is the easiest way.
So basically:
If string1 = string2 Then
'do a thing
End If
I think this String.Equals is what you need.
Dim aaa = "12/31"
Dim a = String.Equals(aaa, "06/30")
a will return false.
If String.Compare(string1,string2,True) Then
'perform operation
EndIf