7
$\begingroup$

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?

$\endgroup$
8
$\begingroup$

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

$\endgroup$
  • $\begingroup$ This doesn't work on my system (v. 10.0.0). The characters are deleted immediately upon entering them. $\endgroup$ – David G. Stork Jan 29 '15 at 1:01
  • $\begingroup$ @DavidG.Stork you're limited to 8 digit characters $\endgroup$ – Mike Honeychurch Jan 29 '15 at 1:07
  • $\begingroup$ Ah yes... digits, not letters or strings. Fine. Thanks. $\endgroup$ – David G. Stork Jan 29 '15 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$ – Mike Honeychurch Jan 29 '15 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 '15 at 3:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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