I have a reprex in the form of a data.table with two variables. One of them is a date column with drop-down calendars. I want a shinyAlert() to pop up when I by mistake type something in a cell of the date column instead of choosing from the calendar. I have inserted shinyAlert() in a relevant place of the snippet but it is popping up automatically as well as when I type a text by mistake or choose from the calendar properly.
Can someone show me what is wrong with my code?
library(shiny)
library(rhandsontable)
library(data.table)
library(shinyalert)
DF <- data.table(Date = as.character(Sys.Date()), col1 = as.numeric(c(1, 2, 3)))
ui <- fluidPage(
useShinyalert(),
rHandsontableOutput("table")
)
server <- function(input, output, session) {
data <- reactiveValues()
observe({
data$df <- as.data.table(DF)
})
observeEvent(input$table, {
if (!is.null(input$table)) {
df <- hot_to_r(input$table)
# Check if the Date column is in a valid format
valid_dates <- !is.na(as.Date(df$Date, format = "%Y-%m-%d"))
if (any(!valid_dates)) {
shinyalert("Invalid Date", "Please enter a valid date format (YYYY-MM-DD).", type = "error")
}
}
})
output$table <- renderRHandsontable({
rhandsontable(data$df) |>
hot_col(1, dateFormat = "YYYY-MM-DD", type = "date")
})
}
shinyApp(ui, server)
This works fine for me. Please note that I am using anydate()
function from anytime
package.
observeEvent(input$table, {
if (!is.null(input$table)) {
df <- hot_to_r(input$table)
print(any(is.na(as.character(anydate(df$Date)))))
if (any(is.na(as.character(anydate(df$Date))))) {
shinyalert("Invalid Date", "Please enter a valid date format.", type = "error")
}
}
})