Cognos文本框提示校验需求:仅允许数字或空值,非法输入禁用运行按钮
Got it, let's sort out this Cognos prompt validation task. You want two text prompts (Prompt1 and Prompt2) to only accept numbers or empty input, and lock the report run button if any prompt has non-numeric, non-empty content. Here's the completed and refined version of your code, plus breakdowns of how it works:
// Grab the current report instance const oCR = cognos.Report.getReport('_THIS_'); // Get references to your two text prompt controls const f1 = oCR.prompt.getControlByName('Prompt1'); const f2 = oCR.prompt.getControlByName('Prompt2'); const prompts = [f1, f2]; // Attach our validation function to each prompt for (let i = 0; i < prompts.length; i++) { prompts[i].setValidator(validate); } // Core validation logic function validate() { let allInputsValid = true; // Check each prompt's input value for (let i = 0; i < prompts.length; i++) { const inputValue = prompts[i].getValue().trim(); // Trim whitespace to handle accidental spaces // Rule: empty is allowed; non-empty must be a valid number if (inputValue !== '' && (isNaN(parseFloat(inputValue)) || !isFinite(inputValue))) { allInputsValid = false; break; // No need to check further once we find invalid input } } // Toggle the run button's enabled state based on validation result const runButton = oCR.prompt.getButton('run'); runButton.setDisabled(!allInputsValid); // Return validation status to update the prompt's built-in validation styling return allInputsValid; }
Key Details to Note:
- Input Check Logic: We trim whitespace first to avoid treating accidental spaces as invalid input. For non-empty values,
parseFloat()+isNaN()+isFinite()ensures we're checking for valid numbers (works for integers, decimals, and negative numbers). - Run Button Control:
oCR.prompt.getButton('run')targets the report's default run button. We disable it only when at least one prompt has invalid input. - Prompt Styling: Returning
allInputsValidtells Cognos to apply its built-in invalid prompt styling (like red borders) to any problematic fields, which helps users spot issues quickly.
Quick Setup Tips:
- Double-check that
Prompt1andPrompt2exactly match the Name property you set for each text prompt in Cognos Report Studio. - Paste this code into an HTML Item on your prompt page, and set the item's type to "Run as JavaScript".
- If you need to restrict inputs to positive numbers only, add an extra check:
inputValue <= 0alongside the number validation.
内容的提问来源于stack exchange,提问作者hbrovell
相关产品推荐
相关产品推荐

