Automatically Add Dashes within TMP_InputField

101 Views Asked by At

The problem is that the dashes are not inserted again after a user deletes or retypes part of a serial key.

Hello, I am working on formatting a license key that lives updates within a TMP_InputField in Unity. When the user is typing a dash should be automatically added after every digits. To be clear I was able to do this however can't get it so when you delete everything and put it in again the dashes should appear. This isn my Start() function has been added as an EventListener to onValueChanged however my suspicion is there is something to do with the length so if anyone could help me that would be great thank you so much?

        void addDashes(string licenseKey)
        {
            int charPos = licenseKey.Length; 
            if ((charPos - dashNum) != 0 && (charPos - dashNum)%5 == 0 && licensingField.text.ToString() != "_" && dashNum < 3)
                {
                    licensingField.text += "-"; 
                    dashNum++; 
                }
        }
3

There are 3 best solutions below

0
MikeVelve On BEST ANSWER
      int charPos = licenseKey.Length;
            if ((charPos - dashNum) != 0 && (charPos - dashNum)%5 == 0 && licenseKey[licenseKey.Length - 1] != '-' && dashNum < 3)
                {
                    licensingField.text += "-"; 
                }
                    dashNum = 0;
                    foreach (char val in licensingField.text)
                    {
                    if(val == '-')
                    {
                        dashNum++; 
                    }
                } 
            }

For anyone interested this took me a long time to find anything online about but this works for the adding a dash dynamically every 5 spots and can be deleted etc. Hope this helps your search

1
CodePirate On

I think the problem lies with the integer dashNum. Because every time you add a dash you increment it. But if you remove one it never gets decremented.

I would suggest that you don't increment dashNum every time you add a dash but rather count the number of dashes and set dashNum equal to the number of counted dashes.

In the following I have an example of what I mean. It is not the nicest one but it should work:

dashNum = 0;

foreach (char val in licensingField.text)
{
  if (val == '-')
  {
    dashNum++;
  }
}

This code would be at the end of your addDashes method

0
derHugo On

Tried a similar thing with date and dots once ... sounds simple but there exist a lot of edge cases to cover! Your user can not only type at the end of the string but also set the caret to any position and insert characters there ...

Instead of validating each character I usually went with:

  • allow user to only type allowed characters but not -
  • on change remove all -
  • then after each x (e.g. 5) characters insert - again
  • recalculate caret position

Something like e.g.

void OnValueChanged(string licenseKey)
{
    // step 1: remove any existing dash
    var rawKey = licenseKey.Replace("-", string.empty);

    // step 1.5: check rawString for validity like e.g. length etc

    // step 2: insert dash after every 5 characters
    var dashedString = Regex.Replace(rawKey, ".{5}", "$0-");

    // step 3: clamp length, covers both, too long user input as well as a trailing `-` edge case from regex 
    // when reaching the full license key length
    if(dashedString.Length > maxLength)
    {
        dashString = dashString.Substring(0, maxLength):
    }
    
    // step 4: write back processed text
   licensingField.SetTextWithoutNotify(dashedString);  
    // step 5: simply increase or decrease the caret position but the length delta
    // Basically +1 if a - was added or -1 if one was removed 
    licensingField.caretPosition += dashedString.Length - licenseKey.length; 
}