When using InputField, whether setting the input type as a Number or String, is there a way to limit the number of characters or digits allowed in the box?

FieldSize appears to set the physical size of the input box, but accommodates larger numbers of digits/characters, simply by enlarging the box in the vertical direction with additional lines, delimiting the end of the line with \ or similar character.

For instance, if I want to limit the input to 5 digits/characters, is this possible, and if so, how is this done?


1 Answer 1


Here is some code I have for entering a 8 digit id number. So this is "out of the box" as is. If you enter more than 8 digits the extra characters are immediately deleted. You can modify to suit your purpose:

InputField[Dynamic[id, (id = Which[
      StringMatchQ[#, DigitCharacter ..] && StringLength[#] >= 8,StringTake[#, 8],
      StringMatchQ[#, DigitCharacter ..], #,
      True, ""]) &], String, ContinuousAction -> True, FieldSize -> 8]

Suggested modification is to remove the digit character constraint if that is more applicable to your needs. The above is for strings of course.

The animated GIF doesn't really do a good job of showing me trying to enter a 9th digit but anyway:

enter image description here

  • $\begingroup$ This doesn't work on my system (v. 10.0.0). The characters are deleted immediately upon entering them. $\endgroup$ Jan 29, 2015 at 1:01
  • $\begingroup$ @DavidG.Stork you're limited to 8 digit characters $\endgroup$ Jan 29, 2015 at 1:07
  • $\begingroup$ Ah yes... digits, not letters or strings. Fine. Thanks. $\endgroup$ Jan 29, 2015 at 1:21
  • $\begingroup$ @DavidG.Stork yes strings, but digit characters. if you enter a non digit character the first to tests fail which leaves you with True, "" in the Which. Obviously you can remove the digit character constraint to enable any string character to be entered. $\endgroup$ Jan 29, 2015 at 1:28
  • $\begingroup$ @MikeHoneychurch This is great, and solves the String half of this problem. Is there a Number version of this for that half of the problem? $\endgroup$
    – iwantmyphd
    Jan 29, 2015 at 3:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.