# Limit characters/digits entered into InputField

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?

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:

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