Discord.js模态框ValidationError求助:期望值为字符串或数字
Discord机器人模态框报错:
ValidationError: Expected the value to be a string or number 问题详情
开发Discord机器人时,调用showModal展示模态框时触发以下错误:ValidationError: Expected the value to be a string or number
引发错误的代码:
await interaction2.showModal( new ModalBuilder() .setTitle("Create new field.") .setCustomId("newtemplatefield") .setComponents( ...[ new ActionRowBuilder<TextInputBuilder>().addComponents( ...[ new TextInputBuilder().setLabel("Field Name").setCustomId("fieldname").setRequired(true) ] ), new ActionRowBuilder<TextInputBuilder>().addComponents( ...[ new TextInputBuilder() .setLabel("Field Description") .setCustomId("fielddesc") .setRequired(true) ] ) ] ) );
解决方法
错误原因
Discord.js的TextInputBuilder必须明确指定输入组件的样式(style),未设置时会触发类型验证错误,这就是你看到的ValidationError的根源。另外代码中多余的扩展运算符(...)可以简化,避免不必要的语法复杂度。
修复后的代码
// 确保已导入TextInputStyle const { TextInputStyle } = require('discord.js'); // ES模块写法:import { TextInputStyle } from 'discord.js'; await interaction2.showModal( new ModalBuilder() .setTitle("Create new field.") .setCustomId("newtemplatefield") .setComponents( new ActionRowBuilder<TextInputBuilder>().addComponents( new TextInputBuilder() .setLabel("Field Name") .setCustomId("fieldname") .setRequired(true) .setStyle(TextInputStyle.Short) // 单行短文本样式 ), new ActionRowBuilder<TextInputBuilder>().addComponents( new TextInputBuilder() .setLabel("Field Description") .setCustomId("fielddesc") .setRequired(true) .setStyle(TextInputStyle.Paragraph) // 多行长文本样式 ) ) );
关键说明
TextInputStyle.Short:适用于单行输入场景(如字段名称)TextInputStyle.Paragraph:适用于多行输入场景(如字段描述)- 必须导入
TextInputStyle,否则会出现未定义错误
内容的提问来源于stack exchange,提问作者Dumbass
相关产品推荐
相关产品推荐

