如何实现可重新触发对应特定提示框的输入验证函数?
如何实现可重新触发对应特定提示框的输入验证函数?
嘿,我完全懂你的困扰——要给好几个不同的提示做输入验证,既想复用代码,又不想每次验证失败弹出的都是干巴巴的“请重新回答”,而是要对应每个问题的专属提示对吧?其实咱们只需要把提示文本、验证规则、错误提示都做成参数,写一个通用的函数就能完美解决这个问题!
思路拆解
核心就是把重复的“弹出提示→验证→失败重新弹”逻辑抽成通用函数,然后让每个具体的输入需求自己提供专属的提示和验证规则,这样函数就能灵活适配所有场景。
具体实现代码
首先写这个通用的输入获取&验证函数:
function getValidInput(promptText, validationFn, errorMessage) { let input; // 循环直到拿到有效输入 do { input = prompt(promptText); // 处理用户点击取消的情况(可以根据需求调整逻辑) if (input === null) { alert("请完成输入后继续哦!"); continue; } // 用传入的验证规则判断输入是否有效 const isValid = validationFn(input.trim()); if (!isValid) { alert(errorMessage); } } while (!validationFn(input.trim()) && input !== null); return input; }
接下来,针对你不同的输入需求,写对应的验证函数:
// 验证非空且不含数字的文本(适用于名字、街道、颜色) function isValidTextWithoutNumbers(input) { return input !== '' && !/\d/.test(input); } // 验证有效年龄(非空、是正数) function isValidAge(input) { const ageNum = Number(input); return input !== '' && !isNaN(ageNum) && ageNum > 0; } // 验证1-10之间的数字 function isValidNumberRange(input) { const num = Number(input); return input !== '' && !isNaN(num) && num >= 1 && num <= 10; }
最后,调用通用函数获取每个输入就可以了:
// 获取妈妈的名字 const mothersFirstName = getValidInput( "What is your mother's first name?", isValidTextWithoutNumbers, "Please refrain from including numbers in your mother's name." ); // 获取童年居住的街道名 const childhoodStreet = getValidInput( "What is the name of the street you grew up on?", isValidTextWithoutNumbers, "Please refrain from including numbers in the street name." ); // 获取童年喜欢的颜色 const favouriteChildhoodColour = getValidInput( "What was your favourite colour as a child?", isValidTextWithoutNumbers, "Please refrain from including numbers in the colour name." ); // 获取当前年龄 const currentAge = getValidInput( "What is your current age?", isValidAge, "Please enter a valid positive number for your age." ); // 获取1-10之间的选择数字 const chosenNumber = getValidInput( "Pick a number between 1 and 10", isValidNumberRange, "Please pick a valid number between 1 and 10." );
这个方案的好处
- 完全复用代码:不用给每个prompt写重复的while/if逻辑,所有输入的流程都统一在通用函数里处理
- 高度灵活:每个输入都可以用专属的提示文本、验证规则和错误提示,完全适配你的五个不同需求
- 易维护:以后要改验证逻辑(比如年龄允许0?或者数字范围调整),只需要修改对应的小验证函数就行,不用动整个流程
最后把你的 fortune teller 逻辑补上就大功告成啦!
备注:内容来源于stack exchange,提问作者Max Saunders
相关产品推荐
相关产品推荐

