kojix2 / LibUI

A portable GUI library for Ruby
MIT License
208 stars 10 forks source link

[Question] Field Edit sign restriction visible in GUI? #53

Closed Delikt closed 2 years ago

Delikt commented 2 years ago

is it possible with LibUI to restrict Signs like %$()= and spaces etc. in an Field Edit?

I imagine if i edit a Field and press defined restricted Signs on my Keyboard the Field will ignore this Signs at all..

Thanks!

AndyObtiva commented 2 years ago

You can simply implement that sort of behavior with the Glimmer DSL for LibUI bidirectional data-binding "on_write" converter (which formats data on write to a model attribute, thus filtering certain characters out if needed).

Example:

require 'glimmer-dsl-libui'

class Contact
  attr_accessor :phone, :username
end

class FieldFormatting
  include Glimmer

  def initialize
    @contact = Contact.new
  end

  def launch
    window('Field Formatting', 300, 100) {
      margined true

      form {
        entry {
          label "Username"
          text <=> [@contact, :username, on_write: ->(val) {val.gsub(/[-%$()=_ ]/, '')}]
        }

        entry {
          label "Phone"
          text <=> [@contact, :phone, on_write: ->(val) {val.gsub(/[^-+.() 0-9]/, '')}]
        }
      }
    }.show
  end
end

FieldFormatting.new.launch

Screen Shot 2022-03-03 at 11 15 01 AM

The implementation restricts username entry to avoid some special characters (no special characters like -%$()=_ though you can restrict more characters or instead declare a negative character list with ^ that removes anything other than a-zA-Z0-9 similarly to what the phone regex does next)

Next, it restricts phone entry to phone format characters -+.() 0-9

p.s. if you have further questions, do not hesitate to ask even if the issue is closed.