having trouble validating input. need to verify that there is at least 1 numeric char and 1 alpha char - validation

As stated in description, I need to validate user input to make sure it is a minimum of 6 characters long and contains 1 numeric character and 1 character from the alphabet.
So far, I've gotten the length validation working but cannot seem to get my numeric validation to function properly. If I enter nothing but numbers, it works, but if I put letters in IE abc123 it will not recognize that there are numbers present.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If txtPassword.TextLength < 6 Then
lblError.Text = "Sorry that password is too short."
ElseIf txtPassword.TextLength >= 6 Then
Dim intCheck As Integer = 0
Integer.TryParse(txtPassword.Text, intCheck)
If Integer.TryParse(txtPassword.Text, intCheck) Then
lblError.Text = "Password set!"
Else
lblError.Text = "Password contains no numeric characters"
End If
End If
End Sub
End Class

how about a regular expression?
using System.Text.RegularExpressions;
private static bool CheckAlphaNumeric(string str)   {
return Regex.Match(str.Trim(), #"^[a-zA-Z0-9]*$").Success;  
}
of if you just up to validating a complex password, then this will do it.
-Must be at least 6 characters
-Must contain at least one one lower case letter,
-One upper case letter,
-One digit and one special character
-Valid special characters are – ##$%^&+=
Dim MatchNumberPattern As String = "^.*(?=.{6,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=]).*$"
If txtPasswordText.Trim <> "" Then
If Not Regex.IsMatch(txtPassword.Text, MatchNumberPattern) Then
MessageBox.Show("Password is not valid")
End If
End If

You may want to use regex to validate if the input contains upper/lower case alpha chars, numbers, special chars.

Related

hidden space in excel

I tried almost all the methods (CLEAN,TRIM,SUBSTITUTE) trying to remove the character hiding in the beginning and the end of a text. In my case, I downloaded the bill of material report from oracle ERP and found that the item codes are a victim of hidden characters.
After so many findings, I was able to trace which character is hidden and found out that it's a question mark'?' (via VBA code in another thread) both at the front and the end. You can take this item code‭: ‭11301-21‬
If you paste the above into your excel and see its length =LEN(), you can understand my problem much better.
I need a good solution for this problem. Therefore please help!
Thank you very much in advance.
Thanks to Gary's Student, because his answer inspired me.
Also, I used this answer for this code.
This function will clean every single char of your data, so it should work for you. You need 2 functions: 1 to clean the Unicode chars, and other one to clean your item codes_
Public Function CLEAN_ITEM_CODE(ByRef ThisCell As Range) As String
If ThisCell.Count > 1 Or ThisCell.Count < 1 Then
CLEAN_ITEM_CODE = "Only single cells allowed"
Exit Function
End If
Dim ZZ As Byte
For ZZ = 1 To Len(ThisCell.Value) Step 1
CLEAN_ITEM_CODE = CLEAN_ITEM_CODE & GetStrippedText(Mid(ThisCell.Value, ZZ, 1))
Next ZZ
End Function
Private Function GetStrippedText(txt As String) As String
If txt = "–" Then
GetStrippedText = "–"
Else
Dim regEx As Object
Set regEx = CreateObject("vbscript.regexp")
regEx.Pattern = "[^\u0000-\u007F]"
GetStrippedText = regEx.Replace(txt, "")
End If
End Function
And this is what i get using it as formula in Excel. Note the difference in the Len of strings:
Hope this helps
You have characters that look like a space character, but are not. They are UniCode 8236 & 8237.
Just replace them with a space character (ASCII 32).
EDIT#1:
Based on the string in your post, the following VBA macro will replace UniCode characters 8236 amd 8237 with simple space characters:
Sub Kleanup()
Dim N1 As Long, N2 As Long
Dim Bad1 As String, Bad2 As String
N1 = 8237
Bad1 = ChrW(N1)
N2 = 8236
Bad2 = ChrW(N2)
Cells.Replace what:=Bad1, replacement:=" ", lookat:=xlPart
Cells.Replace what:=Bad2, replacement:=" ", lookat:=xlPart
End Sub

how to check if password contain at least 1 numeric digit in Visual Basic?

I am a beginner in programming. We use VISUAL BASIC language
1) the password should be at least 6 characters long
2) the password should contain at least one numeric digit and at least one alphabetic character. HOW CAN I CHECK IF PASSWORD CONTAINS AT LEAST 1 NUMERIC DIGIT? I wrote this code:
Function IsValid(input As String) As Boolean
input = input.Trim()
If input.Length < 6 OrElse IsNumeric(input) Then
MessageBox.Show("Your password should be at least 6 characters long,
contain at least one numeric digit and at least one alphabetic character")
Return False
End If
Return True
End Function
Private Sub btnCheck_Click(sender As Object, e As EventArgs) Handles btnCheck.Click
If IsValid(txtInput.Text) Then
MessageBox.Show("Thank you for creating your new password.")
End If
End Sub
HOW CAN I CHECK IF PASSWORD CONTAINS AT LEAST 1 NUMERIC DIGIT?
Thanks
You can add one boolean method ValidatePassword as sown below and pass password entered. To validate numbers function will use regular expression. As you will be checking for only minimum length, one alphabetic char and one numeric digit we will use two regular expressions as ['a-z','A-Z'] for alphabets and ['0-9'] for numbers.
Function ValidatePassword(ByVal pwd As String, Optional ByVal minLength As Integer = 6, Optional ByVal numNumbers As Integer = 1, Optional ByVal numAlphabet As Integer = 1) As Boolean
Dim number As New System.Text.RegularExpressions.Regex("[0-9]")
Dim alphabet As New System.Text.RegularExpressions.Regex("[A-Z],[a-z]")
' Check the length.
If Len(pwd) < minLength Then Return False
' Check for minimum number of occurrences.
If number.Matches(pwd).Count < numNumbers Then Return False
' Check for minimum number of occurrences.
If alphabet.Matches(pwd).Count < numLower Then Return False
' Passed all checks.
Return True
End Function
Get the complete checking for Complex password here http://www.sourcecodester.com/tutorials/visual-basic-net/6828/vbnet-password-complexity.html

Validating the format of a userform textbox entry

I have a UserForm for a database data extractor I'm making. In it there is a TextBox for typing in the part number that the user wants to extract data for. I want to validate that the user has entered the correct format of part number before the bulk of the extractor runs. To do this I need a code to validate that the text is entered in the specific format:
3 Numeric Characters
1 Alphabetic Character or 1 Hyphon
then 5 Numeric Characters
I tried the following validations at first:
'validate that box is not empty
If TextBox1.Value = "" Then
MsgBox ("Sorry, you need to provide an Amount")
TextBox1.SetFocus
Exit Sub
End If
'validate that box is numeric
If Not IsNumeric(TextBox1.Value) Then
MsgBox ("Sorry, must enter a numer")
TextBox1.SetFocus
Exit Sub
End If
But then I realised that I had the problem that there may be an alphabetic char or hyphon in the fourth position.
I would appreciate any suggestions.
Thanks in advance.
A beginner way to check this input is to just chop up the input string and compare the parts as needed:
Const alpha as String = "abcdefghijklmnopqrstuvwxyz-"
Dim strValue as String
Dim msg as String
strValue = TextBox1.Value
'Make sure it's the right LENGTH
If Len(strValue) <> 9 Then
msg = "Please enter the ID as 3 numeric, 1 alpha/hyphen, 5 numeric"
GoTo EarlyExit
End If
'Check the first three for numeric:
If Not IsNumeric(Left(strValue), 3) Then
msg = "The first three characters should be numeric"
GoTo EarlyExit
End If
'Check the middle character, assuming case not sensitive:
If Instr(1, alpha, Lcase(Mid(strValue, 4, 1)) = 0 Then
msg = "The fourth character should be hyphen or alphabet"
GoTo EarlyExit
End If
'Check the last four characters
If Not IsNumeric(Right(strValue, 4)) Then
msg = "The last four characters should be numeric"
GoTo EarlyExit
End If
'If you've gotten here, then the input is validated:
Exit Sub
EarlyExit:
MsgBox msg
TextBox1.SetFocus
End Sub
3 Numeric Characters 1 Alphabetic Character or 1 Hyphon then 5 Numeric Characters

Vb6 .text property for textbox required

I am trying to convert letters to numbers.
I have a sub which ensures only numbers are put into the textbox.
My questions is will the following code work. I have a textbox(for numbers) and combobbox(for letters)
Dim sha As String
Dim stringposition As Long
Dim EngNumber As Long
sha = "abcdefghifjklmnopqrstuvwxyz"
stringposition = InStr(1, sha, Mid(1, cmbEngletter.Text, 1))
MsgBox "stringposition"
EngNumber = (txtManuNo.Text * 10) + stringposition
My only question above would be will the multiplication work with a .text. I believe it won't because it is a string. Please advise then on how to deal with a situation.
You can use CLng() to convert a string to a Long variable
CLng() will throw an error though if it doesn't like the contents of the string (for example if it contains a non-numeric character), so only use it when you are certain your string will only contain numbers
More forgiving is it to use Val() to convert a string into a numeric variable (a Double by default)
I also suggest you look into the following functions:
Asc() : returns the ASCII value of a character
Chr$() : coverts an ASCII value into a character
Left$() : returns the first characters of a string
CStr() : convert a number into a string
I think in your code you mean to show the contents of your variable stringposition instead of the word "stringposition", so you should remove the ""
I do wonder though what you are trying to accomplish with your code, but applying the above to your code gives:
Dim sha As String
Dim stringposition As Long
Dim EngNumber As Long
sha = "abcdefghifjklmnopqrstuvwxyz"
stringposition = InStr(1, sha, Left$(cmbEngletter.Text, 1))
MsgBox CStr(stringposition)
EngNumber = (Val(txtManuNo.Text) * 10) + stringposition
I used Val() because I am not certain your txtManuNo will contain only numbers
To ensure an user can only enter numbers you can use the following code:
Private Sub txtManuNo_KeyPress(KeyAscii As Integer)
Select Case KeyAscii
Case vbKeyBack
'allowe backspace
Case vbKey0 To vbKey9
'allow numbers
Case Else
'refuse any other input
KeyAscii = 0
End Select
End Sub
An user can still input non-numeric charcters with other methods though, like copy-paste via mouse actions, but it is a quick and easy first filter

Number of occurrences in a string

I'm a total noob as far as visual basic goes.
In class I need to do the following: "Write a program that requests a sentence from the user and then records the number of times each letter of the alphabet occurs."
How would I go about counting the number of occurrences in the string?
Loop the chars and add to the list
Dim s As String = "tafata"
Dim count As New Dictionary(Of Char, Integer)()
For i As Integer = 0 To s.Length - 1
count(s(i)) = (If(count.ContainsKey(s(i)), count(s(i)) + 1, 1))
Next
Havent worked with linq that mutch, but i think you can try
Dim s As String = "tafata"
Dim t = From c In s _
Group c By c Into Group _
Select Group
As Dave said, the easiest solution would be to have an array of length 26 (for English), and loop through each character in the string, incrementing the correct array element. You can use the ASCII value of each character to identify which letter it is, then translate the ASCII number of the letter into the corresponding index number:
'Dimension array to 26 elements
Dim LetterCount(0 to 25) As Long
'Temporary index number
Dim tmpIdx As Long
'Temporary character
Dim tmpChar as String
'String to check
Dim checkStr As String
checkStr = "How many of each letter is in me?"
'Change all letters to lower case (since the upper case
'of each letter has a different ASCII value than its
'lower case)
checkStr = LCase(checkStr)
'Loop through each character
For n = 1 to Len(checkStr)
'Get current character
tmpChar = Mid(checkStr, n, 1)
'Is the character a letter?
If (Asc(tmpChar) >= Asc("a")) And (Asc(tmpChar) <= Asc("z")) Then
'Calcoolate index number from letter's ASCII number
tmpIdx = Asc(tmpChar) - Asc("a")
'Increase letter's count
LetterCount(tmpIdx) = LetterCount(tmpIdx) + 1
End If
Next n
'Now print results
For n = 0 to 25
Print Chr(Asc("a") + n) & " - " & CStr(LetterCount(n))
Next n
The quick and dirty way:
Public Function CountInStr(ByVal value As String, ByVal find As String, Optional compare As VbCompareMethod = VbCompareMethod.vbBinaryCompare) As Long
CountInStr = (LenB(value) - LenB(Replace(value, find, vbNullString, 1&, -1&, compare))) \ LenB(find)
End Function
I would count and remove every instance of the first character, and repeat until there are no characters left. Then display the count for each character detected. Much better than looping through once for every possible character, unless you know the possible range of characters is smaller than the length of the sentence.
Imports System.Linq
Dim CharCounts = From c In "The quick brown fox jumped over the lazy dog." _
Group c By c Into Count() _
Select c, Count
from itertools import groupby
sentence = raw_input("Your sentence:")
for char,group in groupby(sorted(sentence.lower())):
print(char+": "+`len(list(group))`)

Resources