0

I have a date formatter that takes in String input from a text field. It formats correctly. However, I am unable to delete the first "/" it keeps 3 strings in UI when using the keyboard delete. I am able to delete the second "/". Any idea why this is happening?

internal class DateFormatter {

    override fun format(input: String): String {
        val cleanInput = input.replace("/", "")
        val textLength = cleanInput.length

        var result = ""
        result = if (textLength >= 2 && textLength < 4) {
            cleanInput.substring(0, 2) + "/" + cleanInput.substring(2)
        } else if (textLength >= 5) {
            (
                cleanInput.substring(0, 2) +
                    "/" + cleanInput.substring(2, 4) + "/" +
                    cleanInput.substring(4)
                ).take(10)
        } else if (input.last() == '/') {
            input.substring(0, input.length - 1)
        } else {
            input
        }

        return result
    }
}
8
  • Your conditions handle textLength < 4 and textLength >= 5. What's supposed to happen when it's exactly 4? Commented Jan 8 at 20:52
  • @Barmar thanks for the callout , I changed it to textLength <= 4, still running into the same issue Commented Jan 8 at 22:01
  • 1
    What is the actual value of input when this happens? What are you expecting it to return, what is it returning instead? Commented Jan 8 at 22:02
  • "it keeps 3 strings in UI when using the keyboard delete" - this doesn't make any sense to me. What three strings? There can only be one string in any one text field. Also, this function is independent of where the input comes from, so the android-textinputedittext tag is not strictly necessary: this function simply takes a string and returns a string. As Barmar asks above, give us an example input string, the expected output string, and the actual output string. Commented Jan 9 at 9:08
  • Sorry, I mean't 3 characters. For Example, if I type in 11/11/2025. Then do a keyboard delete it stops at 11/ and will not let me delete anything past that @Barmar Commented Jan 9 at 15:52

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.