Thursday, February 27, 2014

Two ways to validate a string against a regular expression

The .NET framework provides at least two ways to accomplish regular expression validation.  Microsoft seems to prefer you use RegExStringValidator for simple validation, but as you can see below, it is anything but simple.  I see no reason not to use the RegEx class which is much cleaner.

Use the RegExStringValidator class


Dim MyRegEx As String = "(?=.{8,})(?=(.*\d){1,})(?=(.*[A-Z]){1,})(?=(.*[a-z]){1,})"

Dim MyRegExValidator As New System.Configuration.RegexStringValidator(MyRegEx)

Try

    Dim StringToValidate As String = "gDLDdE12"

    If MyRegExValidator.CanValidate(StringToValidate.GetType()) Then
        MyRegExValidator.Validate(StringToValidate)
    End If

    'If no exception occurs, then the validation succeeded.
    
Catch ex As Exception

    'If an exception occurs, then the validation failed.

End Try


Use the RegEx class


Dim RegExEngine As System.Text.RegularExpressions.Regex = _
    New System.Text.RegularExpressions.Regex("(?=.{8,})(?=(.*\d){1,})(?=(.*[A-Z]){1,})(?=(.*[a-z]){1,})")

If RegExEngine.IsMatch(NewPassword.Text) Then
    'Validation is successful.
Else
    'Validation is not successful.
End If

No comments:

Post a Comment