Formatting form input Digits entries in real time is replacing the typed digit

16 Views Asked by At

I am trying to format a Date field entry in real-time and running into some trouble.

 <input class="form-control ex2" type="text" @bind="salesForm.FollowUpDate" @bind:event="oninput" @onkeydown="FormatForwardDate" placeholder="" />

The Method that I am using is measuring the length and, at the thrid position, add a forward. Continue to the fifth position and add another slash, etc., until it ends at the 11th character.

    private bool isUpdatingDate = false;
    protected void FormatForwardDate(KeyboardEventArgs eventArgs)
    {

        if (!string.IsNullOrWhiteSpace(salesForm.FollowUpDate) && !isUpdatingDate)
        {
            isUpdatingDate = true;

            // Remove non-numeric characters
            var digitsOnly = new string(salesForm.FollowUpDate.Where(char.IsDigit).ToArray());

            if (digitsOnly.Length >= 2)
            {
                digitsOnly = $"{digitsOnly.Substring(0, 2)}/{digitsOnly.Substring(2)}";
            }

            if (digitsOnly.Length >= 5)
            {
                digitsOnly = $"{digitsOnly.Substring(0, 5)}/{digitsOnly.Substring(5)}";
            }

            salesForm.FollowUpDate = digitsOnly;

            // Check if the length is greater than a certain point (e.g., 10) and clear the entry
            if (digitsOnly.Length >= 11)
            {
                salesForm.FollowUpDate = string.Empty;
            }

            isUpdatingDate = false;

            // Set the cursor position after adjustments
            JSRuntime.InvokeVoidAsync("setCursorPosition", "FollowUpDate", digitsOnly.Length);
        }
    }

This JScript was added to adjust the cursor position.

<script>
    window.setCursorPosition = (elementId, position) => {
        const element = document.getElementById(elementId);
        if (element) {
            element.setSelectionRange(position, position);
        }
    };
</script>

The problem that I am having is with the entry and masking tempo. In order to complete the entry and format the string correctly, I must type the third and sixth characters twice. How do I enter the numbers as I type and mask the entry as needed without the double typing effort?

0

There are 0 best solutions below