How to limit the input of decimal point from the keyboard to the text area widget

Description

I want to limit the input of a decimal point in a text area. It’s a function found in calculator apps where after the first input of a decimal point, it wont allow for others to be entered since that would give an invalid number.

What MCU/Processor/Board and compiler are you using?

ESP32 S3

What LVGL version are you using?

version 9

What do you want to achieve?

I want to limit the input of a decimal point in a text area to one

What have you tried so far?

the text area widget already has a callback for keyboard events. I added a second call back in a attempt to limit the input of a decimal point to one.

Code to reproduce

/*You code here*/
static void decimal_restriction_cb(lv_event_t * e) {
  lv_obj_t *ta = (lv_obj_t *)lv_event_get_target(e);
  lv_event_code_t code = lv_event_get_code(e);

  if (code == LV_EVENT_INSERT) {
      const char *txt = (const char *)lv_event_get_param(e);
      // Check if the inserted text is a decimal point
      if (txt && strcmp(txt, ".") == 0) {
          const char *current_text = lv_textarea_get_text(ta);
          // If a decimal point already exists, prevent insertion
          if (strchr(current_text, '.') != NULL) {
                // Remove the last inserted character (the decimal point)
                lv_textarea_delete_char(ta);
                Serial.println("Multiple decimal points prevented");
          }
      }
  }
}

Hi @arbymohamed, maybe you already solved this but this should do the trick:

void decimal_restriction_cb(lv_event_t * e){
    LV_LOG("decimal_restriction_cb was called\n");
    lv_obj_t *ta = (lv_obj_t *)lv_event_get_target(e);
    lv_event_code_t code = lv_event_get_code(e);

    if (code == LV_EVENT_INSERT) {
        const char *txt = (const char *)lv_event_get_param(e);
        
        // Check if the user is trying to insert a decimal point
        if (txt && strcmp(txt, ".") == 0) {
            const char *current_text = lv_textarea_get_text(ta);
            
            // If a decimal point already exists in the text area
            if (strchr(current_text, '.') != NULL) {
                LV_LOG("Multiple decimal points prevented\n");
                // Replace the insert value so nothing gets added
                lv_textarea_set_insert_replace(ta, "");
            }
        }    
    }
}

Also, it’s worth mentioning this function to limit the characters that can be input:

lv_textarea_set_accepted_chars(lv_textarea_0, "0123456789.");