Validate Textbox with Regex

I,m having trouble getting this validation to work on a textbox. I want to validate a valid version format is used.

 New-UDTextbox -Id "AppVersion" -Label "application Version" -OnValidate {
                    if ($EventData -match '^\d+(\.\d+){1,3}$' ) {
                        New-UDValidationResult -Valid
                    }
                    else {
                        New-UDValidationResult -ValidationError 'must be a version'
                    }
                }

This pattern works in PowerShell but when I enter any value into the textbox, I get the validation error. I’m not sure what I am missing.

Which version of PSU?

I never tried that before, but do not seem to be able to get even the example working.

I’m currently running version 4.2.21

1 Like

I tried this and it looks like, if you enter something like “1.2.3” into a textbox, it gets cast to “datetime” which cannot match your regex:

New-UDTextBox -Id "AppVersion" -Label "application Version" -OnChange {
    Show-UDToast -Message "App Version: $EventData" -Duration 10000
    Show-UDToast -Message "EventdataType: $($EventData.GetType())" -Duration 10000
} -OnValidate {
    if($EventData -match "^\d+(\.\d+){1,3}$") {
        New-UDValidationResult -Valid
    } else {
        New-UDValidationResult -ValidationError "App Version needs to match '^\d+(\.\d+){1,3}$'"
    }
}

Interesting! That is strange. I think I solved this by not using $EventData but instead using Get-UDElement.

New-UDTextbox -Id "AppVersion" -Label "application Version" -OnValidate {
                    $inputText = (Get-UDElement -Id 'AppVersion').Value
                    if ($inputText -cmatch '^\d+(\.\d+){1,3}$' ) {
                        New-UDValidationResult -Valid
                    }
                    else {
                        New-UDValidationResult -ValidationError 'must be a version'
                    }
                }
1 Like

I may be a few months too late, but have you tried using a non-Regex method to validate the version?

The easiest way would be to just try to cast it to that class and base your validation on that. This will also allow more types of versions (e.g. without a build, or including a revision) to be used.

$inputText = "1.2.3"
try {
    # Check if the input is a valid version
    [version]$inputText
    New-UDValidationResult -Valid
} catch {
    New-UDValidationResult -ValidationError "Must be a version"
}

As a nice bonus, this method will make your code more readable as well.

1 Like