function - 第一个用于验证用户输入的 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
谢谢你的帮助,小玩意儿
解决方案
在您的代码中,您将文本附加到$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)组成
推荐阅读
- node.js - 邮递员提供产品中的 API 测试不是构造错误
- c - 使用 malloc 设置字符串数组然后清除它
- tensorflow - ValueError:找到了无效的张量“normalized_input_image_tensor”
- c# - Svg.Core - 转换为 PNG 不会呈现表情符号
- android - 无法使用 Retrofit 创建到 ESP8266 服务器的 HTTP POST
- kdb - kdb 中服务器和网关用户管理的良好架构设计
- python - InvalidArgumentError:不兼容的形状:[32] 与 [180]
- c# - 如何在全屏模式下统一检查视频停止或完成?
- node.js - 当我将页面 404 重定向到我的登录页面时出错,它没有 css 并且不接受 Node.js 中的 html
- php - 如何从数据库中获取随机问题包括类别?