2016-07-21 3 views
0

Как и в названии выше мне нужна помощь для хорошей «обратной связи» на входе пользователя ...Powershell сделать хорошую обратную связь ввода

Как будто он печатает 4 вещи в окно ввода и один из тех, вещи должны состоять только из цифр, то второй не должен быть пустым и многое другое ...

Как полей ввода 4 являются:

  • ParID (должны быть только цифры, и мне нужно пользователю введите точно 6
  • Исследовательская группа (3 буквы u петь выпадающий список, и те должны быть только буквы)
  • клиентов (буквы, цифры все разрешено, но не должно быть пустым!)
  • Projectname (такой же, как вход клиента)

Проблема заключается в том, что мой код не работает, потому что он продолжает говорить мне такую ​​же обратную связь, например:

Входной сигнал: «123456» Ошибка: «не число»

Мой код:

$error_message = "Please fill out all of the form fields correctly!`n" #text which will be displayed 
    $error_sign = "Exclamation" #sign veriable -> for a specific sign (picture) which will be displayed 

    if(#the program is going trough all the different types of wrong inputs that could happen and throws an error message! 
     ($ParIDInbox.Text.Length -lt 1) -and 
     ($ResearchGroupInbox.Text.Length -lt 1) -and 
     ($CustomerInbox.Text.Length -lt 1) -and 
     ($ProjectnameInbox.Text.Length -lt 1)) { 
     $error_output = "All fields must be filled out!" 
    } else { 
     Write-Host -f Green "Everything seems right!" 
    } 

    #if($ParIDInbox.Text.Length 
    if([string]::IsNullOrEmpty($ParID)) { 
     $error_output = "ParID must be filled out!" 
    } else { 
     if(($ParID -gt 0) -and ($ParID -lt 6)) { 
      $error_output = "ParID is too short!" 
     } else { 
      $Sort = [int[]][char[]]$ParID #sorts the input ParID into an int and a char array 
       foreach($Value in $ParID) { #goes trough every letter and checks if the ASCII Code for 0-9 is correct! 
        if (!(($Value -ge 48) -and ($Value -le 57))) { 
         $error_output = "ParID is not a number!" 
        } else { 
         #nothing else matters ... 
        } 
       } 
      } 
     }  
    }  
    $error_message = $error_message + "$($error_output)" 

    [System.Windows.Forms.MessageBox]::Show($error_message, "Warning", #messagebox text -> text which will be displayed in the error message box 
    [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::$error_sign) #picture -> picture that will be shown in the window ($error_sign)! 
    $error_output = "" 

EDIT: Оконный Код

$objForm = New-Object System.Windows.Forms.Form #init -> initializing window form 
$objForm.Text = "Input Window v0.5" #name -> the name which will be display in the top border of the window 
$objForm.Size = New-Object System.Drawing.Size(300,290) #size -> set the size of the window 
$objForm.StartPosition = "CenterScreen" #location -> where the window will appear on the screen 
$objForm.FormBorderStyle = 'Fixed3D' #sizing -> fixes the size of the window so you cannot make it bigger  
$OKButton = New-Object System.Windows.Forms.Button #initialization -> initializes the button 
$OKButton.Location = New-Object System.Drawing.Size(75,190) #Location -> where the button is located in the window 
$OKButton.Size = New-Object System.Drawing.Size(75,23) #Size -> defines the size of the button 
$OKButton.Text = "OK" #value -> sets the value of the button to 'OK' 
$objForm.Controls.Add($OKButton) #adding -> adds the button to the window 
$OKButton.Add_Click($OKButton_OnClick) 
$CancelButton = New-Object System.Windows.Forms.Button #initialization -> initializes the button 
$CancelButton.Location = New-Object System.Drawing.Size(150,190) #Location -> where the button is located in the window 
$CancelButton.Size = New-Object System.Drawing.Size(75,23) #Size -> defines the size of the button 
$CancelButton.Text = "Cancel" #value -> sets the value of the button to 'Cancel' 
$CancelButton.Add_Click($CancelButton_Onclick) #closing -> closes the window after clicked 
$objForm.Controls.Add($CancelButton) #adding -> adds the button to the window   
$Info_Label = New-Object System.Windows.Forms.Label #initialization -> initializes the label 
$Info_Label.Location = New-Object System.Drawing.Size(10,220) #Location -> where the label is located in the window 
$Info_Label.Size = New-Object System.Drawing.Size(280,50) #Size -> defines the size of the label 
$Info_Label.Text = "If a browser window does not open up in 30 seconds please restart this script program!" #Info Text 
$objForm.Controls.Add($Info_Label) #adding -> adds the label to the window $ParIDLabel = New-Object System.Windows.Forms.Label #initialization -> initializes the label  
$ParIDLabel.Location = New-Object System.Drawing.Size(10,10) #Location -> where the label is located in the window  
$ParIDLabel.Size = New-Object System.Drawing.Size(280,20) #Size -> defines the size of the label 
$ParIDLabel.Text = "Par ID (6 numbers!)" #value -> sets the value of the Label to 'Par ID (6 numbers)' 
$objForm.Controls.Add($ParIDLabel) #adding -> adds the label to the window  $ParIDInbox = New-Object System.Windows.Forms.TextBox #initialization -> initializes the input box 
$ParIDInbox.Location = New-Object System.Drawing.Size(10,30) #Location -> where the label is located in the window 
$ParIDInbox.Size = New-Object System.Drawing.Size(260,20) #Size -> defines the size of the inputbox 
$ParIDInbox.MaxLength = 6 #sets max. length of the input box to 6 
$objForm.Controls.Add($ParIDInbox) #adding -> adds the input box to the window 
$ResearchGroupLabel = New-Object System.Windows.Forms.Label #initialization -> initializes the label 
$ResearchGroupLabel.Location = New-Object System.Drawing.Size(10,55)  $ResearchGroupLabel.Size = New-Object System.Drawing.Size(280,20) #Size -> defines the size of the label 
$ResearchGroupLabel.Text = "Research Group (3 letters!)" #value -> sets the value of the Label to 'Research Group (3 letters!)' 
$objForm.Controls.Add($ResearchGroupLabel) #adding -> adds the label to the window 
$ResearchGroupInbox = New-Object System.Windows.Forms.ComboBox #initialization -> initializes the combobox (dropdown) 
$ResearchGroupInbox.Location = New-Object System.Drawing.Size(10, 75) 
$ResearchGroupInbox.Size = New-Object System.Drawing.Size(130,28) #Size -> defines the size of the box 
$ResearchGroupInbox.MaxLength = 3 #sets max. length of the input box to 3 
ForEach ($Item in $ResearchGroupShortcuts) { #loop -> put all variables from '$DropDownArray' into '$Item' 
    $ResearchGroupInbox.Items.Add($Item) #adder -> add '$Item' to the dropdown 
} 
$objForm.Controls.Add($ResearchGroupInbox) #adding -> add the dropdown to the window 
$CustomerLabel = New-Object System.Windows.Forms.Label #initialization -> initializes the label 
$CustomerLabel.Location = New-Object System.Drawing.Size(10,100) #Location -> where the label is located in the window 
$CustomerLabel.Size = New-Object System.Drawing.Size(280,20) #Size -> defines the size of the label 
$CustomerLabel.Text = "Customer:" #value -> sets the value of the Label to 'Customer' 
$objForm.Controls.Add($CustomerLabel) #adding -> adds the label to the window 

$CustomerInbox = New-Object System.Windows.Forms.TextBox #initialization -> initializes the input box 
$CustomerInbox.Location = New-Object System.Drawing.Size(10,120) #Location -> where the label is located in the window 
$CustomerInbox.Size = New-Object System.Drawing.Size(260,20) #Size -> defines the size of the inputbox 
$CustomerInbox.MaxLength = 50 #sets max. length of the input box to 50 
$objForm.Controls.Add($CustomerInbox) #adding -> adds the input box to the window  
$ProjectnameLabel = New-Object System.Windows.Forms.Label #initialization -> initializes the label 
$ProjectnameLabel.Location = New-Object System.Drawing.Size(10,140)  $ProjectnameLabel.Size = New-Object System.Drawing.Size(280,20) #Size -> defines the size of the label 
$ProjectnameLabel.Text = "Projectname:" #value -> sets the value of the Label to 'Projectname' 
$objForm.Controls.Add($ProjectnameLabel) #adding -> adds the label to the window 
$ProjectnameInbox = New-Object System.Windows.Forms.TextBox #initialization -> initializes the input box 
$ProjectnameInbox.Location = New-Object System.Drawing.Size(10,160)  $ProjectnameInbox.Size = New-Object System.Drawing.Size(260,20) #Size -> defines the size of the inputbox 
$ProjectnameInbox.MaxLength = 50 #sets max. length of the input box to 50 
$objForm.Controls.Add($ProjectnameInbox) #adding -> adds the input box to the window 
$objForm.Topmost = $True #topmost -> A topmost form is a form that overlaps all the other (non-topmost!) forms! 

$objForm.Add_Shown({$objForm.Activate()}) 
[void] $objForm.ShowDialog() 
+0

Почему бы не использовать регулярное выражение для проверки ввода? Например, '^ \ d {6} $' будет соответствовать ровно шести цифрам. – vonPryz

+0

была бы идеей, но проблема по-прежнему здесь, потому что мои ошибки выведены случайным образом (по крайней мере, похоже, что они случайны). Я не знаю, что не так с моим кодом ^^ –

+0

И я действительно не знаю, как использовать регулярное выражение, потому что я очень новичок в powershell ^^ –

ответ

1

Насколько я помню свою форму из предыдущих вопросов, я могу предложить вам добавлять TextChanged события ypour $ParIDInbox подобные:

#ParID Input Box -> Input box for the Par ID input 
$ParIDInbox = New-Object System.Windows.Forms.TextBox #initialization -> initializes the input box 
$ParIDInbox.Location = New-Object System.Drawing.Size(10,30) #Location -> where the label is located in the window 
$ParIDInbox.Size = New-Object System.Drawing.Size(60,20) #Size -> defines the size of the inputbox 
$ParIDInbox.MaxLength = 6 

$ParIDInbox_OnTextEnter = { 
    if ($ParIDInbox.Text -notmatch '^\d{1,6}$') { 
     $ParIDInbox.Text = $ParIDInbox.Text -replace '\D' 
    } 
} 

$ParIDInbox.add_TextChanged($ParIDInbox_OnTextEnter) 
$objForm.Controls.Add($ParIDInbox) 

Этот код удаляет любой введенный символ, кроме цифры, и имеет параметр ParIDInbox MaxLength, установленный в 6. Таким образом, вам нужно всего лишь проверить минимальную длину o n нажмите кнопку ОК. Я обычно проверяю каждое поле самостоятельно, а не все в одном if заявления - это помогает мне отладить где exatly выброшена ошибка:

if ($ParIDInbox.Text.Length -lt 6) { # or whatever length is ok 
    Show-MessageBox -Type Error -Message "Par ID field should contain 6 digits!" 
} 
elseif ($NextInputBox.Text ...) { ... }# etc 
else { 
    # Your OK button actions here 
} 

И есть Show-MessageBox функции, которая должна быть определена в начале кода:

function Show-MessageBox { 
    param(
     [parameter(Mandatory=$true)] 
     [string]$Message, 
     [Validateset('Error', 'Warning', 'Information')] 
     [string]$Type = 'Information' 
    ) 

    [System.Windows.Forms.MessageBox]::Show($Message, $Type, ` 
     [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::$Type) 
} 
+0

Спасибо человеку (опять ^^) и как мне изменить метод (OnTextChange), чтобы я мог вводить буквы (для другого поля)? или, например, фильтр для специальных знаков, таких как $% (потому что многие из них недопустимы в имени файла! –

+0

@MisterXCT Письма будут '-match [a-zA-Z]' .Если вам также нужны специальные символы, их с осторожностью в соответствии с правилами регулярных выражений. Символы типа '^ [{(\ | $? <>. * +' должны быть экранированы с помощью \.Я могу помочь вам с шаблоном регулярного выражения, если вы предоставите точные критерии, но было бы лучше, если бы вы немного читали о регулярном выражении - это очень полезно, не только для powershell: http://www.regular-expressions.info/ quickstart.html И здесь есть хороший regex cheatsheet: https://www.cheatography.com/davechild/cheat-sheets/regular-expressions/ – n01d

+0

Спасибо и специальные символы, которые я имею в виду: ~ "#% & *: < >?/\ {|}. –

Смежные вопросы