0

I am not having any luck trying to get my first function to work. I need to test three strings to see if the the string is empty, or if any non allowed characters are present. If there is a invalid string, set $Errorstate to 2. and amended a string with a new line of text. If no error is present exit the function. As It stands right now the code accepts all input and passes It through.

#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

Thanks for you help, gizmobrat

1 Answer 1

1

In your code, you are appending text to the variable $Msg, which only exists within the function. One way of achieving what you want is by using Scoping the variables the function needs to append to. This also removes the need for two of the parameters:

# 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

Result:

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

I've changed some of the variable names to be more self-explanatory. Also, on Windows systems, the NewLine is made up of two characters "`r`n" (CRLF)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.