R语言 在Shiny App中的模态对话中使用validate()

pkln4tw6  于 2023-07-31  发布在  其他
关注(0)|答案(1)|浏览(117)

我有一个闪亮的应用程序,其中我有一个模态对话框,它收集一些用户输入,并有一个动作按钮来确认这些输入值。每当用户确认输入时,我希望在使用它们计算新值之前对用户输入执行一些基本的验证测试。我一直在尝试使用闪亮的validate()函数,以便向用户显示自定义的错误消息,但我不知道如何让validate()消息显示在用户的模态对话框中。以下是一个最小可重复的示例。谢谢你的帮助!

library(shiny)

# UI
ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      actionButton("modal", 
                   label = "Modal")
    ),
    mainPanel()
  )
)

# Server
server <- function(input, output, session) {
  modalFunction <- bindEvent(observe({
    showModal(
      modalDialog(
        title = "Modal",
        numericInput("n1", "Number:", value = 0),
        numericInput("n2", "Other number:", value = 0),
        footer = tagList(actionButton("confirm_modal",
                                      label = "Confirm"),
                         modalButton("Cancel"))
      )
    )
  }), input$modal)
  
  modalCalculations <- bindEvent(observe({
    validate(
      need(input$n1 != input$n2, "Warning: Ensure that the two inputs are not equal."),
      need(input$n1 + input$n2 <= 10, "Warning: Ensure that the two inputs do not sum to greater than 10.")
    )
    
    showModal(
      modalDialog(
        renderText(paste0("Success! The sum is ", input$n1 + input$n2, " and the difference is ", input$n1 - input$n2, ".")),
        footer = tagList(modalButton("Return"))
      )
    )
  }), input$confirm_modal)
}

# Run the application 
shinyApp(ui = ui, server = server)```

字符串

0ve6wy6x

0ve6wy6x1#

根据文档(?validate
validate()提供了方便的机制,用于验证输出是否具有成功呈现所需的所有输入。
因此,将validate()移动到第二个modal的renderText(也就是输出)中,以显示错误消息:

modalCalculations <- bindEvent(observe({
  showModal(
    modalDialog(
      renderText({
        validate(
          need(
            input$n1 != input$n2,
            "Warning: Ensure that the two inputs are not equal."
          ),
          need(
            input$n1 + input$n2 <= 10,
            "Warning: Ensure that the two inputs do not sum to greater than 10."
          )
        )

        paste0(
          "Success! The sum is ", input$n1 + input$n2,
          " and the difference is ", input$n1 - input$n2, "."
        )
      }),
      footer = tagList(modalButton("Return"))
    )
  )
}), input$confirm_modal)

字符串


的数据

相关问题