Skip to main content
December 19, 2011
Answered

How to restrict length of EditText control?

  • December 19, 2011
  • 1 reply
  • 906 views

All,

How do I restrict the length of an EditText to accept ONLY 3 characters.

The editText.characters property sets a default size, but the user can still type more than 3 characters in the field.

This topic has been closed for replies.
Correct answer CarlosCanto

I got it!!!

var win = new Window("dialog", "Limit 3");

var txtLimit3 = win.add("edittext");

txtLimit3.characters = 5;

txtLimit3.onChanging = function (){

          howmany = txtLimit3.text;

          if (howmany.length > 3){

                    txtLimit3.text = "";

                    txtLimit3.textselection = howmany.slice(0,3)

                    }

          }

txtLimit3.active = true;

win.show();

1 reply

Inspiring
December 19, 2011

I don't think you can restrict the UI in this way… You can check the result and loop back clearing the content and making it active again…

CarlosCanto
Community Expert
CarlosCantoCommunity ExpertCorrect answer
Community Expert
December 21, 2011

I got it!!!

var win = new Window("dialog", "Limit 3");

var txtLimit3 = win.add("edittext");

txtLimit3.characters = 5;

txtLimit3.onChanging = function (){

          howmany = txtLimit3.text;

          if (howmany.length > 3){

                    txtLimit3.text = "";

                    txtLimit3.textselection = howmany.slice(0,3)

                    }

          }

txtLimit3.active = true;

win.show();

December 21, 2011

Ha! Thanks, I was just about to post a similar snippet for prosterity...

I had hoped that there was just a "maxchars" property for text fields, like in other scripting languages!