Search code examples
validationinputbasic

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


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

Solution

  • 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