Limiting an input box to certain characters

Welcome Forums General PowerShell Q&A Limiting an input box to certain characters

This topic contains 2 replies, has 2 voices, and was last updated by

 
Participant
3 months, 2 weeks ago.

  • Author
    Posts
  • #109867

    Participant
    Points: 26
    Rank: Member

    I am working on a GUI wrapper for a small program, and am trying to limit the characters allowed in a couple of input boxes to only numbers and periods (e.g. IP, DNS, etc.). I can get the numbers by simply matching any non-digit character (see below) but this also negates any periods.

        $IPInput = New-Object System.Windows.Forms.TextBox
            $IPInput.Location = New-Object System.Drawing.Point(445, 60)
            $IPInput.Size = New-Object System.Drawing.Size(170, 20)
            $IPInput.TextAlign = 'Center'
            $IPInput.MaxLength = 16
            $IPInput.add_TextChanged({
                if($IPInput.Text -match '\D') {
                    $IPInput.Text = $IPInput.Text -replace '\D'
                        if($IPInput.Text.Length -gt 0) {
                            $IPInput.Focus()
                            $IPInput.SelectionStart = $IPInput.Text.Length
                        }
                }
            })
    

    I am guessing I will need to use a regex of some sort to capture all numeric values and not disallow periods, but to be honest regex still makes my eyes bleed. I tried something like this:

    if(!($IPInput.Text -match '[0-9].')) { ...
    

    But it did not work for me. Hoping someone can suggest a simply way to accomplish this.

  • #109913

    Participant
    Points: 894
    Helping Hand
    Rank: Major Contributor

    Below is the regex for ip address.

    '192.168.1.1' -match "^(\d{1,3}\.){3}\d{1,3}$"
    
    'a.b' -match "^(\d{1,3}\.){3}\d{1,3}$"
    
  • #110314

    Participant
    Points: 26
    Rank: Member

    I ended up going with the below. It is ugly but it works.

    if($IPInput.Text -match '[A-Z!@#$%^&*();;_=+?/|\`"`~{[}}-]')
    

The topic ‘Limiting an input box to certain characters’ is closed to new replies.