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.

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:
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.
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.
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.
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.
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 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.
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.
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).
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.
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
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.
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.
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 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.
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.
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.
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.
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.
PAD doesn't expose a native "am I attended or unattended?" variable, but you can infer it from context:
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.
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.
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.
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.
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.
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:
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
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.
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:
Add a Parse JSON action on FlowResultJSON with the schema you defined
Add a Condition branching on FlowStatus equals FAILED
In the failure branch:
errorCode to route to different handlers (validation failures go to a different handler than runtime errors)VALIDATION_ERROR, send an adaptive card to the submitting user with the specific field and messageOUTPUT_MISSING or OUTPUT_INVALID_FORMAT, create an incident in your ticketing systemIn 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.
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:
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]".
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
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 charactersOrderTotal (Text): Numeric, range 100.00–50000.00, max 2 decimal placesRequiredDate (Text): ISO 8601, must be at least 3 business days from today and no more than 90 days outLineItemCodes (List): Between 1 and 100 items, each matching ^ITEM-\d{4}$RunMode (Text): Either "Attended" or "Unattended"Part 1: Build the ValidateInputs subflow
ValidateInputsSetValidationFailure helper subflow that accepts FailedField, ValidationMessage, and FailedValue as local variables and builds the JSON error stringValidationPassed to True at the end of the subflow (only reached if all checks pass)Part 2: Run-mode branching
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 correctionRunMode = "Unattended" and ValidationPassed = False, write the error JSON to a file at C:\RPA\Logs\PO_Validation_%TodayDate%.log and exit the flowPart 3: Output validation
POConfirmationID matches ^CONF-\d{10}$ProcessedLineCount equals the count of LineItemCodesFlowStatus = "FAILED" with errorCode OUTPUT_VALIDATION_ERRORPart 4: Integration
FlowStatus (Text) and FlowResultJSON (Text) as output variables"not_a_number", and a RequiredDate of yesterdayMistake: 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.
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.
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.
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.
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.
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.
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.
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:
FlowStatus + FlowResultJSON) for clean branchingThe 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:
Power Automate Desktop & RPA