Wicked Smart Data
LearnInsightsAboutContact
Sign InLet's Build
LearnInsightsAboutContact
Sign InLet's Build
Wicked Smart Data

Intelligence, automation, and expert execution — plus an elite library of free knowledge. We turn complexity into competitive advantage.

Start a conversation

Platform

  • Learning Paths
  • Insights
  • RSS Feed

Company

  • About
  • Contact
  • Work With Us

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Wicked Smart Data. All rights reserved.

Intelligence · Automation · Advantage

All Insights
Power Automate

Implementing Desktop Flow Input Sanitization and Output Validation in Power Automate Desktop: Enforcing Data Type Contracts, Boundary Checks, and Structured Error Responses Across Attended and Unattended Run Modes

Most RPA failures aren't caused by bad selectors or application timeouts — they're caused by bad data that the bot never questioned. This lesson teaches you to build production-grade validation gates that enforce data type contracts, sanitize string inputs, check numeric and date boundaries, and return structured error responses your cloud flows can actually act on. Covers both attended and unattended run modes with concrete PAD implementation patterns.

🔥 Expert27 min readNov 19, 2026Updated Nov 19, 2026
Implementing Desktop Flow Input Sanitization and Output Validation in Power Automate Desktop: Enforcing Data Type Contracts, Boundary Checks, and Structured Error Responses Across Attended and Unattended Run Modes
On this page
  • Introduction
  • Prerequisites
  • Why Input Sanitization Is Not Optional at Scale
  • Defining a Data Type Contract for Your Flow
  • Building the Validation Gate Subflow
  • Structuring the Error Response Object
  • String Input Sanitization Techniques
  • Trimming Whitespace
  • Null and Empty String Checks
  • Regex Pattern Matching
  • Length Boundary Checks
  • Sanitizing for JSON Embedding
  • Numeric and Date Boundary Validation
  • Numeric Range Checks
  • Decimal Precision Validation
  • Date Validation
  • List and Collection Boundary Checks
  • Collection-Level Checks
  • Element-Level Checks
  • Run-Mode-Aware Validation Behavior
  • Detecting Run Mode
  • Attended Mode: Interactive Correction
  • Unattended Mode: Silent Failure with Rich Logging
  • Output Validation: Before You Return Anything
  • Why Output Validation Matters
  • Cross-Output Consistency Checks
  • Integrating with the Cloud Flow Error Handling Layer
  • Handling Sensitive Inputs Safely
  • Hands-On Exercise
  • Common Mistakes & Troubleshooting
  • Validating After Application Launch
  • Single Generic Error Messages
  • Forgetting Locale-Sensitive Number Parsing
  • Not Escaping Received Values in JSON Error Strings
  • Validation Subflow That Modifies Input Variables
  • Infinite Retry Loops in Attended Mode
  • Output Validation That Trusts the Application
  • Summary & Next Steps

Implementing Desktop Flow Input Sanitization and Output Validation in Power Automate Desktop: Enforcing Data Type Contracts, Boundary Checks, and Structured Error Responses Across Attended and Unattended Run Modes

Introduction

Imagine your unattended bot runs at 2 AM against an ERP system, processing invoice batches. A cloud flow passes in a vendor ID that someone fat-fingered as "VND-12 34" — a space slipped into the middle. Your bot cheerfully types that into a search field, the application returns zero results, and the bot interprets the empty screen as "no invoices to process." No error is raised. No alert fires. By morning, 47 invoices are sitting unprocessed, aging past SLA, and nobody knows why.

This is the class of failure that input sanitization and output validation is specifically designed to prevent. It's not glamorous work, but it separates production-grade automation from fragile scripts. When you enforce data type contracts at flow entry points and validate outputs before passing them upstream, you turn ambiguous runtime failures into explicit, diagnosable errors. You also make your flows dramatically easier to test, monitor, and hand off to colleagues who didn't build them.

By the end of this lesson, you'll be able to design and implement a full validation layer for Power Automate Desktop flows — one that handles type coercion, boundary enforcement, structured error packaging, and run-mode-aware behavior. You'll understand not just the mechanics but the architectural reasoning behind each pattern.

What you'll learn:

  • How to enforce data type contracts on inputs passed from cloud flows, triggering flows, and manual attended runs
  • Techniques for sanitizing string inputs (trimming, encoding, regex validation) before they reach application UI
  • How to implement numeric, date, and list boundary checks with meaningful failure messages
  • How to build structured JSON error response objects that cloud flows can branch on intelligently
  • How to adapt your validation strategy for attended versus unattended run modes, including silent failure vs. interactive prompting

Prerequisites

You should be comfortable with the core Power Automate Desktop environment. If you need a refresher on the basics, start with Getting Started with Power Automate Desktop: Installing, Recording, and Running Your First Desktop Flow. You should also understand how inputs and outputs flow between cloud flows and desktop flows — if that's new territory, read Triggering Desktop Flows from Cloud Flows: Passing Inputs and Returning Outputs before continuing.

A solid grasp of Power Automate Desktop's variable system will help significantly. Review Variables, Lists, and Data Tables in Power Automate Desktop: A Complete Practitioner's Guide if you're not confident with custom objects and data tables. You'll also want familiarity with subflows and error handling patterns, since the validation framework we're building sits on top of those primitives.


Why Input Sanitization Is Not Optional at Scale

There's a common misconception that input validation is primarily a web security concern — something you do in APIs and forms to prevent SQL injection. In desktop automation, the stakes are different but equally real.

Desktop flows operate on live production systems. They click real buttons, type into real fields, and submit real forms. An unsanitized input doesn't just cause a logic error — it can corrupt database records, trigger duplicate transactions, lock application sessions, or silently skip processing entire record sets. The bot doesn't question the data it receives; it just executes.

The problem compounds in unattended mode. When a human runs an attended flow and something looks wrong, they notice. When an unattended bot encounters an unexpected empty string where it expected a numeric vendor ID, it either throws an unhandled exception (which at least surfaces in run history) or — worse — proceeds with incorrect data because the flow's error handling wasn't designed to catch that specific failure mode.

The solution is a validation gate: a subflow that runs before any application interaction, checks every input against a declared contract, and either normalizes the data or fails fast with a structured error message. Fast failure is a feature, not a bug.

Key insight

The goal of input validation in RPA is not to fix bad data — it's to detect bad data early, fail with enough diagnostic information that the source system can correct and retry, and prevent the bot from causing downstream damage while operating on garbage inputs.

For flows that are part of larger orchestration patterns, see Building a Resilient Unattended RPA Orchestration Framework in Power Automate Desktop — the validation patterns in this lesson integrate directly with queue-driven architectures.


Defining a Data Type Contract for Your Flow

Before you write a single validation action, you need to declare what your flow expects. This is your data type contract — a formal specification of each input variable's type, format, allowable range, and nullability.

Here's an example contract for an invoice processing flow:

Input Variable Type Format / Constraints Nullable?
VendorID Text Pattern: ^VND-\d{5}$ No
InvoiceAmount Number Range: 0.01 – 999999.99 No
InvoiceDate Text ISO 8601: YYYY-MM-DD No
CostCenterCode Text Length: exactly 6 chars, alphanumeric No
ApproverEmail Text Valid email pattern Yes (skipped if empty)
LineItems List Min 1 item, max 500 items No

Document this contract somewhere that survives beyond your head — a SharePoint page, a comment block at the top of your flow, or a dedicated input schema table. The contract is your specification. The validation subflow is its enforcement mechanism.

Tip

Treat the data type contract as a versioned artifact. When a triggering cloud flow changes what it sends, the contract version should change too, and your validation subflow should be updated in lockstep. Version mismatches are a leading cause of silent data corruption in production RPA.


Building the Validation Gate Subflow

The validation gate is a dedicated subflow — call it ValidateInputs — that your main flow calls as its very first action, before any application is launched or any UI interaction occurs. If validation fails, ValidateInputs sets a structured error output and the main flow exits cleanly without touching any application.

You'll work with Subflows and Reusable Logic in Power Automate Desktop to build this. The key design principle: the validation subflow should be stateless and pure. It reads inputs, it sets validation results. It doesn't launch apps, it doesn't write files, it doesn't have side effects.

Structuring the Error Response Object

Power Automate Desktop doesn't have native object types, but you can simulate a structured response using a custom object (available in PAD through the Set variable action with a custom object literal, or by building a data table). The pattern I recommend is a JSON string, because it survives the round-trip back to a cloud flow as a text output variable and can be parsed by Power Automate's Parse JSON action.

Your structured error response should contain:

{
  "status": "FAILED",
  "errorCode": "VALIDATION_ERROR",
  "field": "VendorID",
  "message": "VendorID 'VND-12 34' does not match required pattern ^VND-\\d{5}$",
  "receivedValue": "VND-12 34",
  "timestamp": "2024-03-15T14:23:11",
  "runMode": "Unattended"
}

In a successful run, the same output variable holds:

{
  "status": "SUCCESS",
  "errorCode": null,
  "field": null,
  "message": null,
  "receivedValue": null,
  "timestamp": "2024-03-15T14:23:11",
  "runMode": "Unattended"
}

This consistent structure means your cloud flow's downstream error handling doesn't have to guess at the shape of a failure. It runs Parse JSON on the output, checks status, and branches accordingly.

Here's how you build the success response in PAD using a Set Variable action:

SET ValidationResult TO $'''{"status": "SUCCESS", "errorCode": null, "field": null, "message": null, "receivedValue": null, "timestamp": "%CurrentDateTime%", "runMode": "%RunMode%"}'''

And a failure response (you'll parameterize these values through the flow):

SET ValidationResult TO $'''{"status": "FAILED", "errorCode": "VALIDATION_ERROR", "field": "%FailedField%", "message": "%ValidationMessage%", "receivedValue": "%FailedValue%", "timestamp": "%CurrentDateTime%", "runMode": "%RunMode%"}'''

Warning

Special characters in input values — particularly double quotes, backslashes, and newlines — will break your JSON string if interpolated directly. Before embedding a received value in the error JSON, sanitize it with a Replace Text action that escapes backslashes and quotes. We'll cover this sanitization pattern in detail in the next section.


String Input Sanitization Techniques

String inputs are the most common source of validation failures, and they require both sanitization (cleaning the value) and validation (checking it meets the contract). These are distinct operations — sanitization happens first.

Trimming Whitespace

The most common string defect is leading or trailing whitespace, usually from copy-paste in upstream forms. PAD's Trim text action handles this, but you should apply it universally to every string input as the very first step, before any other check.

# Always trim first
Trim text %VendorID% trimming: Both sides -> TrimmedVendorID
SET VendorID TO TrimmedVendorID

Don't skip this for fields where you "don't expect" whitespace. That expectation will be violated exactly once, in production, at the worst possible moment.

Null and Empty String Checks

PAD represents unset inputs as empty strings. Check nullability before any downstream processing:

IF VendorID = '' THEN
    SET FailedField TO 'VendorID'
    SET ValidationMessage TO 'VendorID is required and cannot be empty'
    SET FailedValue TO '[empty]'
    CALL SetValidationFailure
    EXIT SUBFLOW
END

Create a SetValidationFailure subflow that sets the ValidationResult JSON and a boolean flag ValidationPassed = False. The EXIT SUBFLOW stops further checks once a failure is found (fail-fast pattern).

Regex Pattern Matching

For structured string inputs like vendor IDs, cost center codes, email addresses, and date strings, regex matching is the right tool. PAD's Match text with regular expression action returns the match and a success boolean.

Match text %VendorID% for regular expression '^VND-\d{5}$' -> Matches, MatchCount

IF MatchCount = 0 THEN
    SET FailedField TO 'VendorID'
    SET ValidationMessage TO 'VendorID must match pattern VND-NNNNN (e.g., VND-00147)'
    SET FailedValue TO %VendorID%
    CALL SetValidationFailure
    EXIT SUBFLOW
END

For email validation, the regex ^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$ covers the vast majority of real-world cases without being so strict it rejects valid addresses.

Note

PAD's regex engine uses .NET regex syntax. Anchors (^ and $), character classes (\d, \w), and quantifiers ({5}, +, *) all work as expected. Named groups and lookaheads are supported. What doesn't work well is multi-line mode — if you're validating text that might contain newlines (from a text area, for example), strip or escape them before pattern matching.

Length Boundary Checks

For fields with length constraints, use the Get subtext action's length property or convert to a list of characters:

GET LENGTH OF TEXT %CostCenterCode% -> CostCenterLength

IF CostCenterLength <> 6 THEN
    SET FailedField TO 'CostCenterCode'
    SET ValidationMessage TO 'CostCenterCode must be exactly 6 characters, received ' + CostCenterLength + ' characters'
    SET FailedValue TO %CostCenterCode%
    CALL SetValidationFailure
    EXIT SUBFLOW
END

Sanitizing for JSON Embedding

When you interpolate a received input value into a JSON error response string, any quotes or backslashes in the value will corrupt the JSON. Run this sanitization before building the error message:

# Escape backslashes first (must be first)
Replace text %FailedValue% to replace: '\' replace with: '\\' -> SafeValue
# Then escape double quotes
Replace text %SafeValue% to replace: '"' replace with: '\"' -> SafeValue
# Replace newlines
Replace text %SafeValue% to replace: (newline character) replace with: '\n' -> SafeValue

This is admittedly verbose, but it's the difference between a parseable error response and a broken JSON blob that causes a second failure when your cloud flow tries to parse it.


Numeric and Date Boundary Validation

Numeric Range Checks

PAD's input variables typed as numbers should be validated for range, sign, and — for financial amounts — decimal precision.

# Convert to number if input arrives as text (common from cloud flow text inputs)
Convert text %InvoiceAmountRaw% to number -> InvoiceAmount

IF CONVERSION FAILED THEN
    SET FailedField TO 'InvoiceAmount'
    SET ValidationMessage TO 'InvoiceAmount must be a numeric value, received: ' + InvoiceAmountRaw
    SET FailedValue TO %InvoiceAmountRaw%
    CALL SetValidationFailure
    EXIT SUBFLOW
END

IF InvoiceAmount < 0.01 OR InvoiceAmount > 999999.99 THEN
    SET FailedField TO 'InvoiceAmount'
    SET ValidationMessage TO 'InvoiceAmount must be between 0.01 and 999999.99, received: ' + InvoiceAmount
    SET FailedValue TO %InvoiceAmount%
    CALL SetValidationFailure
    EXIT SUBFLOW
END

Notice the two-stage check: first convert (which can fail), then validate range. These are distinct failure modes requiring distinct error messages. A downstream support engineer needs to know whether the value was "not a number" or "out of range" — those require completely different fixes.

Decimal Precision Validation

For currency amounts, you may also need to verify that the value has no more than two decimal places. This is trickier in PAD because there's no native decimal-precision action. Use a string conversion approach:

Convert number %InvoiceAmount% to text with format '0.##########' -> AmountAsText
Match text %AmountAsText% for regular expression '^\d+(\.\d{1,2})?$' -> Matches, MatchCount

IF MatchCount = 0 THEN
    SET FailedField TO 'InvoiceAmount'
    SET ValidationMessage TO 'InvoiceAmount has more than 2 decimal places, which is invalid for currency'
    SET FailedValue TO %InvoiceAmount%
    CALL SetValidationFailure
    EXIT SUBFLOW
END

Date Validation

Date strings require both format validation (is this a valid ISO 8601 date?) and semantic validation (is this date within an acceptable range?). PAD's Convert text to datetime action will tell you if the format is parseable:

Convert text %InvoiceDateRaw% to datetime using format 'yyyy-MM-dd' -> InvoiceDate

IF CONVERSION FAILED THEN
    SET FailedField TO 'InvoiceDate'
    SET ValidationMessage TO 'InvoiceDate must be in YYYY-MM-DD format, received: ' + InvoiceDateRaw
    SET FailedValue TO %InvoiceDateRaw%
    CALL SetValidationFailure
    EXIT SUBFLOW
END

For semantic validation — say, you won't process invoices dated more than 90 days in the past or any date in the future — compute the boundary dates and compare:

Get current date and time -> TodayDateTime
Subtract from datetime %TodayDateTime% subtract: 90 days -> EarliestAllowed

IF InvoiceDate < EarliestAllowed OR InvoiceDate > TodayDateTime THEN
    SET FailedField TO 'InvoiceDate'
    SET ValidationMessage TO 'InvoiceDate must be between 90 days ago and today'
    SET FailedValue TO %InvoiceDateRaw%
    CALL SetValidationFailure
    EXIT SUBFLOW
END

Tip

When validating dates from ERP systems or legacy applications, watch out for locale-specific formats. A field that displays 15/03/2024 on a European machine will fail an ISO 8601 parse. If your bot runs on machines with different regional settings, normalize date strings to ISO 8601 at the cloud flow level before passing them to the desktop flow, or add locale-aware parsing logic to your conversion step.


List and Collection Boundary Checks

For inputs that are lists (line items in an invoice, record IDs for batch processing), you need to validate both the collection itself and, in some cases, each element within it.

Collection-Level Checks

GET COUNT OF %LineItems% -> LineItemCount

IF LineItemCount < 1 THEN
    SET FailedField TO 'LineItems'
    SET ValidationMessage TO 'LineItems must contain at least one item'
    SET FailedValue TO '[empty list]'
    CALL SetValidationFailure
    EXIT SUBFLOW
END

IF LineItemCount > 500 THEN
    SET FailedField TO 'LineItems'
    SET ValidationMessage TO 'LineItems exceeds maximum batch size of 500. Received: ' + LineItemCount
    SET FailedValue TO LineItemCount
    CALL SetValidationFailure
    EXIT SUBFLOW
END

The upper bound check (500 items) isn't just about data integrity — it's a performance guard. A bot that iterates over 50,000 line items wasn't designed for that workload, and failing early is far better than running for six hours and either crashing or degrading the target application.

Element-Level Checks

For lists where each element must meet a specific contract (a list of account codes, for example), loop through the list and validate each element. Track the first failure and report it with its position:

SET ItemIndex TO 0
FOR EACH CurrentItem IN LineItems
    SET ItemIndex TO ItemIndex + 1
    
    # Validate element format
    Match text %CurrentItem% for regular expression '^\d{10}$' -> Matches, MatchCount
    
    IF MatchCount = 0 THEN
        SET FailedField TO 'LineItems[' + ItemIndex + ']'
        SET ValidationMessage TO 'Item at index ' + ItemIndex + ' is not a valid 10-digit account code: ' + CurrentItem
        SET FailedValue TO %CurrentItem%
        CALL SetValidationFailure
        EXIT SUBFLOW
    END
END

Including the index in the field name (LineItems[3]) is enormously helpful for debugging. Without it, you know a line item is bad but you have to scan all of them to find which one.


Run-Mode-Aware Validation Behavior

Here's where the design gets interesting. The right response to a validation failure in an attended flow is different from the right response in an unattended flow. If a human is sitting at the machine, you can prompt them to correct the input and retry. If the bot is running headlessly at 2 AM, there's nobody to prompt — you need to fail fast, log richly, and exit cleanly.

This is why your validation framework needs to be run-mode-aware. See Attended vs Unattended RPA: Choosing a Run Mode and Configuring Machines in Power Automate for the broader context on how run modes differ architecturally.

Detecting Run Mode

PAD doesn't expose a native "am I attended or unattended?" variable, but you can infer it from context:

  1. Pass it as an explicit input. The simplest approach. Add a text input variable called RunMode to your flow's input contract, set it to "Attended" or "Unattended" in the triggering cloud flow, and in attended scenarios, default it to "Attended" via a Set Variable action at the start of the main flow.

  2. Use an environment variable. Set a Windows environment variable on attended machines (say, PAD_RUN_MODE=Attended) and read it at flow start. Unattended machines leave this variable unset, so its absence indicates unattended mode.

  3. Check for active session. Use a PowerShell Run script action to check whether the current session is interactive: [System.Environment]::UserInteractive returns True in an interactive session, False in a service context.

The explicit input approach is the most maintainable for flows triggered by cloud flows. The PowerShell check is the most reliable for flows that might be triggered by multiple mechanisms.

Attended Mode: Interactive Correction

In attended mode, a validation failure can trigger a dialog prompting the user to correct the value:

IF RunMode = 'Attended' AND FailedField = 'VendorID' THEN
    Display input dialog with 'Validation Error' message: 
        'VendorID format is invalid. Please enter a valid VendorID (format: VND-NNNNN)' 
        default: %VendorID% 
        -> CorrectedValue, ButtonPressed
    
    IF ButtonPressed = 'OK' THEN
        SET VendorID TO CorrectedValue
        # Re-run validation from the top
        CALL ValidateInputs
    ELSE
        # User cancelled — treat as unattended failure
        CALL SetValidationFailure
        EXIT SUBFLOW
    END
END

Warning

Be careful with recursive correction loops in attended mode. If you re-call ValidateInputs after a correction, make sure you have a maximum retry counter (say, 3 attempts) to prevent an infinite loop where the user keeps entering invalid values and the dialog keeps reappearing. After the maximum retries, fall through to the structured failure path.

Unattended Mode: Silent Failure with Rich Logging

In unattended mode, skip all dialogs and go directly to structured failure:

IF RunMode = 'Unattended' THEN
    # Build structured error response (already covered above)
    CALL SetValidationFailure
    # Log to file or event log before exiting
    CALL WriteValidationErrorToLog
    EXIT FLOW WITH ERROR
END

The WriteValidationErrorToLog subflow should write the full ValidationResult JSON to a date-stamped log file and optionally append a row to a SharePoint list or database table for centralized monitoring. When you're running fleets of unattended bots as described in Managing Machines and Machine Groups for Scalable Unattended Automation in Power Automate, centralized validation failure logs are essential for identifying systemic input problems versus one-off data quality issues.


Output Validation: Before You Return Anything

Input validation gets most of the attention, but output validation is equally important. Before your flow returns outputs to the calling cloud flow, you should verify that those outputs are:

  1. Present (not empty when they're supposed to have a value)
  2. Well-formed (the right format)
  3. Internally consistent (a confirmation number extracted from the application matches the expected format)
  4. Plausible (a quantity processed equal to the quantity submitted, within tolerance)

Why Output Validation Matters

Consider an invoice processing bot that submits an invoice and then scrapes the confirmation number from the application's success screen. If the submission actually failed but the error was in a different UI element that the bot didn't check, the bot might return an empty string as the confirmation number. The cloud flow receives this, doesn't know the submission failed, and marks the invoice as processed.

Output validation catches this. Before returning ConfirmationNumber, check:

IF ConfirmationNumber = '' THEN
    SET OutputValidationResult TO '{"status": "FAILED", "errorCode": "OUTPUT_MISSING", 
        "field": "ConfirmationNumber", "message": "Application did not return a confirmation number after submission", 
        "timestamp": "%CurrentDateTime%"}'
    EXIT FLOW WITH ERROR
END

Match text %ConfirmationNumber% for regular expression '^INV-\d{8}$' -> Matches, MatchCount
IF MatchCount = 0 THEN
    SET OutputValidationResult TO '{"status": "FAILED", "errorCode": "OUTPUT_INVALID_FORMAT",
        "field": "ConfirmationNumber", "message": "Confirmation number does not match expected format INV-NNNNNNNN, received: ' + ConfirmationNumber + '",
        "timestamp": "%CurrentDateTime%"}'
    EXIT FLOW WITH ERROR
END

Cross-Output Consistency Checks

For batch operations, validate that quantities are consistent:

# We submitted 15 line items. The application confirmed 15 were processed.
IF ProcessedCount <> SubmittedCount THEN
    SET OutputValidationResult TO '{"status": "FAILED", "errorCode": "OUTPUT_QUANTITY_MISMATCH",
        "field": "ProcessedCount", "message": "Expected ' + SubmittedCount + ' records processed, application confirmed ' + ProcessedCount + '",
        "timestamp": "%CurrentDateTime%"}'
    EXIT FLOW WITH ERROR
END

This kind of check catches partial-failure scenarios where the application processes some records but silently drops others — a failure mode that is otherwise nearly invisible to the calling system.

Key insight

Output validation is your integrity check against the application you're automating. You cannot trust that every application will reliably report failures. ERP systems, legacy apps, and mainframe terminal emulators in particular are notorious for showing "success" screens even when the backend transaction failed. Build output validation that verifies the expected result, not just the absence of an explicit error.


Integrating with the Cloud Flow Error Handling Layer

The structured error response pattern only delivers its full value if the calling cloud flow is designed to consume it properly. Here's the integration pattern:

Your desktop flow exposes two output variables:

  • FlowStatus: Either "SUCCESS" or "FAILED" (a simple text variable for quick branching)
  • FlowResultJSON: The full structured JSON response (the detailed diagnostic payload)

In the cloud flow, after the "Run desktop flow" action:

  1. Add a Parse JSON action on FlowResultJSON with the schema you defined

  2. Add a Condition branching on FlowStatus equals FAILED

  3. In the failure branch:

    • Check errorCode to route to different handlers (validation failures go to a different handler than runtime errors)
    • For VALIDATION_ERROR, send an adaptive card to the submitting user with the specific field and message
    • For OUTPUT_MISSING or OUTPUT_INVALID_FORMAT, create an incident in your ticketing system
    • For any validation failure, do NOT mark the source record as processed — requeue it for correction
  4. In the success branch: continue normal processing

This two-variable pattern (FlowStatus for branching + FlowResultJSON for diagnostics) is intentional. Cloud flows can branch on simple string equality without needing to parse JSON. JSON parsing is only needed when you want to extract the specific error details. This separation keeps your cloud flow logic cleaner and faster to evaluate.


Handling Sensitive Inputs Safely

An important constraint: your validation error messages should include enough information to diagnose the problem without exposing sensitive data in logs. For fields like ApproverEmail or any financial data:

  1. Mask the value in error messages. Instead of "received: john.doe@acme.com", report "received: j***.d**@acme.com" or simply "received: [redacted - 24 chars]".

  2. Don't include sensitive values in the JSON response. The FlowResultJSON travels back through the cloud flow and may be logged in run history, which is visible to anyone with environment admin access.

For handling sensitive variables properly, see Handling Credentials Securely in Desktop Flows: Sensitive Variables and Azure Key Vault.

Here's a masking utility you can call before building error responses:

# Mask all but first and last character, replace middle with asterisks
GET LENGTH OF TEXT %SensitiveValue% -> ValueLength
GET SUBTEXT OF %SensitiveValue% start: 0 length: 1 -> FirstChar
GET SUBTEXT OF %SensitiveValue% start: ValueLength - 1 length: 1 -> LastChar
SET MaskLength TO ValueLength - 2
SET MaskChars TO ''
LOOP MaskLength TIMES
    SET MaskChars TO MaskChars + '*'
END LOOP
SET MaskedValue TO FirstChar + MaskChars + LastChar

Hands-On Exercise

Build a complete validation gate for a purchase order automation flow. The flow accepts the following inputs from a cloud flow:

  • PONumber (Text): Must match ^PO-\d{6}$
  • SupplierCode (Text): Must be exactly 8 uppercase alphanumeric characters
  • OrderTotal (Text): Numeric, range 100.00–50000.00, max 2 decimal places
  • RequiredDate (Text): ISO 8601, must be at least 3 business days from today and no more than 90 days out
  • LineItemCodes (List): Between 1 and 100 items, each matching ^ITEM-\d{4}$
  • RunMode (Text): Either "Attended" or "Unattended"

Part 1: Build the ValidateInputs subflow

  1. Create a new subflow called ValidateInputs
  2. Create a SetValidationFailure helper subflow that accepts FailedField, ValidationMessage, and FailedValue as local variables and builds the JSON error string
  3. Implement all six validation checks in sequence, using the fail-fast pattern (exit subflow on first failure)
  4. For the date check, you'll need to calculate business days — implement a simple loop that increments a date counter, skipping Saturdays and Sundays, until you've counted 3 business days forward from today
  5. Set a boolean output variable ValidationPassed to True at the end of the subflow (only reached if all checks pass)

Part 2: Run-mode branching

  1. If RunMode = "Attended" and ValidationPassed = False, display a dialog showing the failed field and message, with a Retry button that re-calls the validation after allowing input correction
  2. If RunMode = "Unattended" and ValidationPassed = False, write the error JSON to a file at C:\RPA\Logs\PO_Validation_%TodayDate%.log and exit the flow

Part 3: Output validation

  1. After the simulated application interaction (you can mock this with a Set Variable action), validate that:
    • POConfirmationID matches ^CONF-\d{10}$
    • ProcessedLineCount equals the count of LineItemCodes
  2. If output validation fails, set FlowStatus = "FAILED" with errorCode OUTPUT_VALIDATION_ERROR

Part 4: Integration

  1. Expose FlowStatus (Text) and FlowResultJSON (Text) as output variables
  2. Test with deliberately malformed inputs: a PONumber with a space, an OrderTotal of "not_a_number", and a RequiredDate of yesterday

Common Mistakes & Troubleshooting

Validating After Application Launch

Mistake: Running the application first and then validating inputs inside the application interaction block.

Why it's bad: You've already consumed a machine license, launched a potentially slow application, and possibly locked a session before discovering the data was bad. Fail before you open anything.

Fix: ValidateInputs is always the first action in Main, before any Launch application, Attach to running program, or similar actions.


Single Generic Error Messages

Mistake: Setting ValidationMessage = "Input validation failed" for all failures.

Why it's bad: This is useless for debugging. The person who needs to fix the upstream data has no idea which field failed or why.

Fix: Every validation check produces a field-specific, value-specific message that explains exactly what was wrong and what was expected.


Forgetting Locale-Sensitive Number Parsing

Mistake: Using Convert text to number on a value like "1,234.56" on a machine with a European locale set, where the comma is a decimal separator.

Why it's bad: The conversion will either fail or produce 1.234 (treating the decimal point as a thousands separator), causing a silent magnitude error.

Fix: Normalize numeric strings to remove thousands separators before conversion, or validate the format with regex before parsing. Use Replace text to strip commas before converting. For deployment across international machine fleets, test your validation logic on machines with non-US locale settings.


Not Escaping Received Values in JSON Error Strings

Mistake: Directly interpolating %FailedValue% into a JSON string without escaping.

Why it's bad: A value like "Acme "Super" Supplies" will produce malformed JSON that crashes your cloud flow's Parse JSON action.

Fix: Always run the escape sequence (backslash → double-quote → newline) on any external value before embedding it in JSON.


Validation Subflow That Modifies Input Variables

Mistake: Having ValidateInputs sanitize inputs (trim, normalize) while also setting error state, so the main flow uses sanitized values only if it checks the right flag.

Why it's bad: The sanitized values exist in local subflow scope (or modify main flow variables via shared variable state), creating hard-to-track execution paths. If a future developer reorders the subflow calls, they'll get subtle bugs.

Fix: Separate sanitization and validation into distinct subflows. SanitizeInputs runs first and updates the input variables in place (trim, case normalize, strip excess whitespace). ValidateInputs then runs on the already-sanitized values and only sets pass/fail state. This separation makes both subflows easier to test and reason about.


Infinite Retry Loops in Attended Mode

Mistake: Re-calling ValidateInputs after a user correction without a retry counter.

Why it's bad: A user who consistently enters invalid data (or is confused about the format) will get stuck in an infinite dialog loop with no way to cancel.

Fix: Maintain a RetryCount variable. After 3 failed correction attempts, fall through to the structured failure path and exit with an appropriate error message.


Output Validation That Trusts the Application

Mistake: Assuming the application's "Success" screen means the transaction succeeded.

Why it's bad: This is empirically false for a surprising number of enterprise applications. SAP, for instance, can display a green header while simultaneously posting a warning message that indicates the posting was incomplete.

Fix: Validate the specific output artifact (confirmation number, record ID, status code) rather than the absence of an error. For applications that behave like this, see Automating SAP GUI Interactions with Power Automate Desktop for SAP-specific validation patterns.


Summary & Next Steps

You've built a complete mental model and implementation framework for input sanitization and output validation in Power Automate Desktop. Here's what we covered:

  • Data type contracts: Formalizing what your flow expects before writing a single validation action
  • String sanitization: Trimming, escaping, and regex-matching string inputs before they touch any application
  • Numeric and date boundary validation: Two-stage convert-then-validate, range checks, precision checks, and semantic date validation
  • List boundary and element validation: Collection-level size guards and element-level contract enforcement
  • Structured JSON error responses: A consistent, parseable output format that cloud flows can branch on intelligently
  • Run-mode-aware behavior: Interactive correction dialogs for attended mode, silent rich-logging for unattended mode
  • Output validation: Verifying that application outputs match expected formats and quantities before returning them upstream
  • Integration with the cloud flow layer: The two-variable pattern (FlowStatus + FlowResultJSON) for clean branching

The most important thing to take away: validation isn't a last-minute quality gate — it's an architectural commitment. A flow that validates its inputs and outputs is a flow that fails predictably, debugs quickly, and earns the trust of the production systems it integrates with.

Where to go next:

  • For flows that connect to multiple applications, add validation at each application boundary — not just at flow entry. See Automating Multi-Application Workflows in Power Automate Desktop for the architecture.
  • Extend your logging subflow to write structured error records to a database table for fleet-level monitoring. The patterns in Monitoring and Troubleshooting Desktop Flow Runs at Scale complement the validation layer you've built here directly.
  • If your flows process data from CSV or text file inputs rather than cloud flow inputs, the same validation patterns apply — but you'll need to add record-level validation inside your loop. See Reading and Writing to CSV and Text Files in Power Automate Desktop for the file I/O patterns that pair with this validation framework.
Work With Us

From insight to implementation

Reading is the start. When you're ready to build the data, automation, or AI systems behind it, our team turns strategy into shipped results.

Let's Build

Power Automate Desktop & RPA

Previous

Automating Windows Printer and Print Queue Management in Power Automate Desktop: Selecting Printers, Submitting Print Jobs, and Monitoring Queue Status in Unattended RPA Workflows

Related Insights

Power AutomateExpert

Automating Recurring Approval Workflows with Expiry Dates in Power Automate: Triggering on SharePoint Date Columns, Notifying Owners, and Routing Renewals Through Multi-Step Sign-Off

28 min
Power AutomatePractitioner

Implementing Power Automate Child Flow Fan-Out and Result Aggregation Patterns for Parallel High-Volume Record Processing Without Exceeding Action and Concurrency Limits

23 min
Power AutomatePractitioner

Automating Windows Printer and Print Queue Management in Power Automate Desktop: Selecting Printers, Submitting Print Jobs, and Monitoring Queue Status in Unattended RPA Workflows

22 min

On this page

  • Introduction
  • Prerequisites
  • Why Input Sanitization Is Not Optional at Scale
  • Defining a Data Type Contract for Your Flow
  • Building the Validation Gate Subflow
  • Structuring the Error Response Object
  • String Input Sanitization Techniques
  • Trimming Whitespace
  • Null and Empty String Checks
  • Regex Pattern Matching
  • Length Boundary Checks
  • Sanitizing for JSON Embedding
  • Numeric and Date Boundary Validation
  • Numeric Range Checks
  • Decimal Precision Validation
  • Date Validation
  • List and Collection Boundary Checks
  • Collection-Level Checks
  • Element-Level Checks
  • Run-Mode-Aware Validation Behavior
  • Detecting Run Mode
  • Attended Mode: Interactive Correction
  • Unattended Mode: Silent Failure with Rich Logging
  • Output Validation: Before You Return Anything
  • Why Output Validation Matters
  • Cross-Output Consistency Checks
  • Integrating with the Cloud Flow Error Handling Layer
  • Handling Sensitive Inputs Safely
  • Hands-On Exercise
  • Common Mistakes & Troubleshooting
  • Validating After Application Launch
  • Single Generic Error Messages
  • Forgetting Locale-Sensitive Number Parsing
  • Not Escaping Received Values in JSON Error Strings
  • Validation Subflow That Modifies Input Variables
  • Infinite Retry Loops in Attended Mode
  • Output Validation That Trusts the Application
  • Summary & Next Steps