【问题标题】:having trouble validating input. need to verify that there is at least 1 numeric char and 1 alpha char验证输入时遇到问题。需要验证至少有 1 个数字字符和 1 个字母字符
【发布时间】:2017-02-24 11:28:17
【问题描述】:

如描述中所述,我需要验证用户输入以确保其长度至少为 6 个字符,并且包含 1 个数字字符和 1 个字母表字符。

到目前为止,我已经完成了长度验证,但似乎无法让我的数字验证正常工作。如果我只输入数字,它可以工作,但如果我在 IE abc123 中输入字母,它将无法识别存在数字。

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

【问题讨论】:

标签: validation input basic


【解决方案1】:

正则表达式怎么样?

using System.Text.RegularExpressions; 

private static bool CheckAlphaNumeric(string str)   { 
   return Regex.Match(str.Trim(), @"^[a-zA-Z0-9]*$").Success;  
 }

如果您只是验证一个复杂的密码,那么就可以了。

-必须至少为 6 个字符

-必须至少包含一个小写字母,

-一个大写字母,

-一个数字和一个特殊字符

-有效的特殊字符是 –@#$%^&+=

    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

【讨论】:

    【解决方案2】:

    您可能希望使用正则表达式来验证输入是否包含大写/小写字母字符、数字、特殊字符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-30
      • 2017-06-02
      • 1970-01-01
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      • 2010-12-28
      • 1970-01-01
      相关资源
      最近更新 更多