Oliver
Oliver

Reputation: 181

Using RegEx to Validate User Input

RESOLUTION - Provided By Wiktor - I have implemented this into my question.

Validating user input while they're typing to match the following format - 11A11

    Private Sub RegexFormatterExample(sender As Object, e As EventArgs)

    Dim txt As TextBox = sender
    Dim pattern As String = ""

    Select Case txt.Name
        Case "txt_example"
            pattern = "^\d{1,2}(?:(?<=^\d{2})[A-Z]\d{0,2})?$"
        Case Else
            pattern = "^\d{1,2}(?:(?<=^\d{2})[A-Z]\d{0,2})?$"
    End Select

    Dim strText As String = txt.Text

    While Not Regex.IsMatch(strText, pattern) AndAlso Not strText = ""
        strText = strText.Substring(0, strText.Length - 1)
    End While

    txt.Text = strText
    txt.Select(txt.Text.Length, 0)
End Sub

I have also attached a .TextChanged handler to the specified txtbox.

The provided answer only allows the user to type in the following format which is what I asked for.

What I want

Thanks Wiktor!

Edit

Further to this scenario there is a case where the user has the ability to enter only a minus symbol rather than passing an empty string for where they don't know the value.

To implement this I amended the RegEx pattern to the following. Regex Demo

I am not sure if this is the most efficient way but it seems to be working for me.

Upvotes: 1

Views: 245

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626861

You may use

^\d{1,2}(?:(?<=^\d{2})[A-Z]\d{0,2})?\z

See the .NET regex demo online (\z is replaced with \r?$ since the demo is run against a single multiline string).

Details

  • ^ - start of string
  • \d{1,2} - one or two digits
  • (?: - start of a non-capturing group:
    • (?<=^\d{2}) - a positive lookbehind check: there must be two digits at the start of the string immediately to the left of the current position
    • [A-Z] - an uppercase letter
    • \d{0,2} - 0, 1 or 2 digits
  • )? - end of the non-capturing group, repeat 1 or 0 times (i.e. make it optional)
  • (?:[A-Z]\d{0,2})? - an optional sequence of an uppercase letter and then 0, 1 or 2 digits
  • \z - the very end of string (no \n is allowed at the end of the string).

Upvotes: 1

juha
juha

Reputation: 76

Maybe you can trim \n off (if any) and use

"^[0-9]{2}[A-Z][0-9]{2}$"

instead?

Upvotes: 0

Related Questions