10

I would like my Shiny app (in R) to limit the number of characters a user can input in response to a textInput command.

I can request the user to limit to 50 characters and can have the app send him a message if he does not, but it would be better if he were prevented from overrunning the limit in the first place.

Suggestions appreciated.

Dan Flath
  • 101
  • 1
  • 3

2 Answers2

8

You can't add custom attribute to textInput, you could probably be able to write custom function to generate input, but it will be easier to do this in javascript:

shinyjs::runjs("$('#inputName').attr('maxlength', 50)")
jcubic
  • 61,973
  • 54
  • 229
  • 402
  • Putting this in my server.r file worked great, thanks! – Iain Jun 21 '17 at 20:03
  • 1
    I think it's a great idea to do this client side as in the above. (Yes, the `shinyjs::` call is server-side, but the actual limit enforcement is done by the client browser, as it should be). – maxheld Feb 23 '21 at 10:32
  • 4
    I've logged an [issue](https://github.com/rstudio/shiny/issues/3305) over at shiny to support `maxlength` in shiny. – maxheld Feb 23 '21 at 10:33
1

For example by using shinyBS and stringr packages:

library(stringr)
library(shinyBS)
string <- "Destrier ipsum dolor cold weirwood, consectetur adipisicing elit, sed full of terrors incididunt green dreams always pays his debts. Ut in his cups sandsilk, no foe may pass spearwife nisi ut aliquip we do not sow. Duis aute warrior feed it to the goats death before disgrace maidenhead dog the seven pariatur. Rouse me not cupidatat non proident, suckling pig culpa qui officia deserunt mollit we light the way."

    observe({
        if(str_length(string)>50) {
          newstring <-str_sub(string, end=50)
          createAlert(session, inputID = "alert_anchor",
            message = "You exceeded 50 character limit!",
            dismiss = TRUE,
            block = FALSE
            append = TRUE)
            updateTextInput(session, inputID, value = newstring)
    }

    })

    # remember to create alert to shiny UI
    # bsAlert(inputID = "alert_anchor")

Demo page for shinyBS:ShinyBS

Mikael Jumppanen
  • 2,436
  • 1
  • 17
  • 29