Zapier JavaScript validation - Choose alternative value when string is empty

I’m working with Zapier to handle webhook data and I need to validate if a field contains data. If the primary field is empty, I want to use a backup value instead.

Basically I have two name fields coming from a form. Users can enter a preferred name in FIELD1 or leave it blank. If it’s blank, I want to use their full name from FIELD2.

Here’s my JavaScript code in Zapier:

var result = 'Default Name';
if(inputData.FIELD1 != '') {
  result = {username: inputData.FIELD1};
} else {
  result = {username: inputData.FIELD2};
}
return result;

The code seems to work in testing but fails when the zap actually runs. The username variable doesn’t get populated in the next step even though it shows up correctly in the task history. Has anyone dealt with this issue before?

I’ve hit this exact issue before with Zapier automation. You’re starting result as a string then switching it to an object - that’s what’s messing things up. Even if it works in testing, Zapier’s live environment doesn’t like the inconsistency. Drop the initial string assignment and do this instead:

var result;
if(inputData.FIELD1 && inputData.FIELD1.trim() !== '') {
  result = {username: inputData.FIELD1};
} else {
  result = {username: inputData.FIELD2};
}
return result;

I threw in a trim() check too - sometimes fields have whitespace that looks empty but isn’t. Zapier’s test vs live modes can be really annoying, but keeping your variable types consistent usually fixes these weird issues.

check if inputData.FIELD1 is actually undefined, not just an empty string. zapier sometimes sends undefined values that won’t match your != ‘’ condition. try inputData.FIELD1 || inputData.FIELD2 for a quick fallback, or add if(inputData.FIELD1 && inputData.FIELD1.length > 0) to be safe.

The real problem might be that you’re not handling null values properly. I ran into the same thing with Zapier webhooks - empty form fields sometimes come through as null instead of empty strings, which breaks your comparison logic. Your condition inputData.FIELD1 != '' won’t catch nulls.

Try this instead:

var result = {
  username: (inputData.FIELD1 && inputData.FIELD1.toString().trim()) || inputData.FIELD2 || 'Default Name'
};
return result;

This converts to string first, then checks if it exists and has content after trimming whitespace. The fallback chain makes sure you always get a valid username. I’ve found this works reliably across different webhook sources where field handling can be inconsistent.