Search code examples
powershelltextbox

How to make a powershell textbox accepts only alphabetical or numeric character?


I'm making with powershell a windows form textbox and need users type only numeric or alphabetical characters.

I've found this using in c#

System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "^[a-zA-Z ]")

May be there is a way to adapt it in powershell or not

A part of my code

...
# TextBox
$textbox = New-Object System.Windows.Forms.TextBox
$textbox.AutoSize = $true
$textbox.Location = New-Object System.Drawing.Point(150,125)
$textbox.Name = 'textbox_sw'
$textbox.Size = New-Object System.Drawing.Size(220,20)
$textbox.Text = "Max11car"
$textbox.MaxLength = 11
$form.Add_Shown({$form.Activate(); $textbox.Focus()}) # donne le focus à la text box
#$textbox = New-Object System.Text.RegularExpressions.Regex.IsMatch($textbox.Text, "^[a-zA-Z0-9 ]")
#$textbox = New-Object System.Text.RegularExpressions.Regex($textbox.Text, "^[a-zA-Z0-9 ]")
...

I expect the output will be something like this AbCDef45 and not Ab%$58


Solution

  • I suggest you add an Add_TextChanged() method to the textbox that immediately strips off any characters you do not allow.

    Something like this:

    $textBox.Add_TextChanged({
        if ($this.Text -match '[^a-z 0-9]') {
            $cursorPos = $this.SelectionStart
            $this.Text = $this.Text -replace '[^a-z 0-9]',''
            # move the cursor to the end of the text:
            # $this.SelectionStart = $this.Text.Length
    
            # or leave the cursor where it was before the replace
            $this.SelectionStart = $cursorPos - 1
            $this.SelectionLength = 0
        }
    })
    

    Regex details:

    [^a-z 0-9]    Match a single character NOT present in the list below:
                  - a character in the range between “a” and “z”
                  - the space character “ ”
                  - a character in the range between “0” and “9”