首页 > 解决方案 > 第一个用于验证用户输入的 Powershell 函数和正则表达式

问题描述

我没有任何运气试图让我的第一个功能正常工作。我需要测试三个字符串以查看字符串是否为空,或者是否存在任何不允许的字符。如果存在无效字符串,则将 $Errorstate 设置为 2。并用新的文本行修改字符串。如果不存在错误,则退出该函数。就目前而言,代码接受所有输入并通过它。

#Error Function
Function Test-isGood($Vaule,$Errtxt,$Msg,$State){
   if($Vaule -eq ""){
        $Msg = $Msg + "`n" + "Please Fill in the"+ "$Errtxt" + "Box"
        $State = 2
    }
    if ($Vaule -match "\A[^a-z0-9 _&-]+\Z") {
        $State = $State
    }else{
        $Msg = $Msg + "`n" + "Please Use A-Z, a-z and 0-9 in the"+"$Errtxt" +"Box"
        $State = 2
    }
    $Errorstate = $state
    $ErrorMessage = $Msg

}

#Name Holders
$Temp1 = "S0#"
$Temp2 = "Job Name"
$Temp3 = "Contractor"

#Call Error Function
Test-isGood $TextBox1.Text $Temp1 $ErrorMessage $Errorstate
Test-isGood $TextBox2.Text $Temp2 $ErrorMessage $Errorstate
Test-isGood $TextBox3.Text $Temp3 $ErrorMessage $Errorstate

谢谢你的帮助,小玩意儿

标签: functionpowershelluser-input

解决方案


在您的代码中,您将文本附加到$Msg仅存在于函数中的变量中。实现您想要的一种方法是使用范围限定函数需要附加到的变量。这也消除了对两个参数的需要:

# Error Function
Function Test-IsGood([string]$Value, [string]$TextBox){
    if ([string]::IsNullOrWhiteSpace($Value)) {
        $Script:ErrorMessage += "`r`nPlease Fill in the '$TextBox' Box"
        $Script:Errorstate = 2
    }
    if ($Value -match "[^a-z0-9 _&-]") {
        $Script:ErrorMessage += "`r`nPlease Use A-Z, a-z and 0-9 in the '$TextBox' Box"
        $Script:Errorstate = 2
    }
}

# Name Holders
$TextBoxName1 = "S0#"
$TextBoxName2 = "Job Name"
$TextBoxName3 = "Contractor"

# initialize the variables (here using script scope)
$Script:ErrorMessage = ''
$Script:Errorstate   = 0

#Call Error Function
Test-isGood '' $TextBoxName1
Test-isGood '&*' $TextBoxName2
Test-isGood '@@@' $TextBoxName3

# show the message and state
$ErrorMessage
$Errorstate

结果:

Please Fill in the 'S0#' Box
Please Use A-Z, a-z and 0-9 in the 'Job Name' Box
Please Use A-Z, a-z and 0-9 in the 'Contractor' Box
2

我已经更改了一些变量名称以使其更加不言自明。此外,在 Windows 系统上,换行符由两个字符“`r`n”(CRLF)组成


推荐阅读