Perspective: Limit text input field to regex pattern?

v8.1.0

I want to let the user enter either blank or a number. I can’t use the numeric entry field as it doesn’t allow blanks, so I next option is to use a text input limited to numeric characters. Can I do this?

I don’t know of anything built-in, but you could turn off defer updates and use a property change script similar to here (Limit Characters in a Textbox when Typing).

Scratch what I said, I didn’t see the defer updates there… I’ll give it a go, cheers!

1 Like

Well… it sort of works. It works technically, but practically it’s deceptive. While the props.text property doesn’t contain non-numerics, the text displayed in the input field itself still does :frowning:

Also, this is my change script on the props.text property:

	import re
	pattern = '[^0-9]' # remove text that matches this pattern
	text = currentValue.value
	res = re.search(pattern, text)
	
	if res is not None:
		text = re.sub(pattern, '', text)
		self.props.text = text
1 Like

re.sub substitutes all non-numeric (all characters that match the pattern) characters for no characters (effectively removing them)

Yeah as soon as I posted I realized I hadn’t read all the way to the bottom. My bad.

1 Like

Really I could have just used re.sub without search, but I figured it was better not to keep writing to the field every time the user types a character :face_with_monocle:

I tried your script in a TextField component and it works for me in properties and in display. I tried it in designer and a client. The non-numeric will show up but it disappears almost instantly. This is in a coordinate container I use for test type things. 8.0.10.

image

This is what I get:

Even after pressing enter it doesn’t update it

And your onChange script is attached to text? I can’t see it in your video.

Yep. You can see that the “ddf” I entered don’t appear in the text in the props, so it must be working in the background, just doesn’t seem to update the display :thinking:

I think the problem is that you’re actively setting the text during a value change, and so the back-end schema is correct, but the front-end input is out-of-sync. I’ll look into it.

In the meantime, I found a hacky workaround:

  1. Place a custom property: stripped_text.
  2. Bind TextField.custom.stripped_text to props.text.
  3. Place a change script on TextField.custom.stripped_text which performs your logic.
    4a. On the Text Field, you’ll need to use the onKeyPress Event to capture Key events for Enter, Tab, and Escape, and you’ll also need to use onBlur to capture the occasional click-out.
    4b. The onKeyPress and onBlur Events should use the following script.
    desired = self.custom.stripped_text
	self.props.text = ''
	self.props.text = desired

The NEF does allow blanks. Just set the format to none.