How to restrict number of character in Native text field

I have used text field to store username and want to restrict user name should contain maximum 7 character. I expect native text field should not accept more than 7 character… is there any way to do that? [import]uid: 92740 topic_id: 20737 reply_id: 320737[/import]

You could add a listener; http://developer.anscamobile.com/reference/index/nativenewtextfield

That listener could check the string length and if the length is greater than 7 you could clear any characters typed after the 7th.

That’s just off the top of my head, there are likely other ways of handling it, too :slight_smile:

Peach [import]uid: 52491 topic_id: 20737 reply_id: 81446[/import]

I used that listener but How can i clear the character ?

[lua] --How to clear the text field here
print( "TextField Object is: " … tostring( getObj() ) )

if ( “began” == event.phase ) then
– This is the “keyboard has appeared” event

elseif ( “ended” == event.phase ) then

userName=tostring( getObj().text );
print(#userName)
if #userName > 7 then
–WHAT TO DO HERE ? it wont effect…
end

print( "Text entered = " … tostring( getObj().text ) ) – display the text entered

elseif ( “submitted” == event.phase ) then
native.setKeyboardFocus( nil )
end
[/lua]

If i check the size in ended phase no use… where i have to do this?.. text field should not receive the text after 7th character [import]uid: 92740 topic_id: 20737 reply_id: 81474[/import]

Run this code on it’s own for a demo;

[lua]display.setStatusBar (display.HiddenStatusBar)

local field

limitField = function (event)
if (string.len(field.text)) > 7 then
field.text = field.text:sub(1,7)
end
end

field = native.newTextField(10, 10, 100, 20, limitField)[/lua]

That’s just off the top of my head but should work fine, let me know if there are any issues.

Peach :slight_smile: [import]uid: 52491 topic_id: 20737 reply_id: 81629[/import]

Thanks a lot for your time. I tried your code but after 7th character, it will add the character at the beginning of the text field… [import]uid: 92740 topic_id: 20737 reply_id: 82094[/import]

Is this in the Xcode simulator or Corona simulator? Also, which version of Corona are you using?

I just testing using 704 and it works fine in both simulators.

Please let me know.

Peach :slight_smile: [import]uid: 52491 topic_id: 20737 reply_id: 82135[/import]

I’m using corona simulator 2011.704(2011.12.8) but tried it in android device becoz windows simulator don’t show native text field.

vnshetty:) [import]uid: 92740 topic_id: 20737 reply_id: 82147[/import]

Ah I see.

Unfortunately some textfield stuff will behave differently on Android; it would be worth posting in the Android sub forum to ask for a solution as another Android dev may have a workaround for you.

I’m afraid I deal almost exclusively with iOS and don’t actually have an Android device here at the moment to test. [import]uid: 52491 topic_id: 20737 reply_id: 82177[/import]