Skip to content

Commit 976ac09

Browse files
committed
Improve OTP input sanitization and focus handling
Refactored the OnInput method to sanitize input by allowing only digits, handle pasted or fast-typed multiple digits by using the last digit, and clear invalid input both in state and DOM. Updated the input field if the raw value doesn't match the sanitized digit and streamlined focus movement logic. Removed unnecessary else branches and debug statements for cleaner code.
1 parent f997370 commit 976ac09

1 file changed

Lines changed: 22 additions & 17 deletions

File tree

blazorbootstrap/Components/Form/OTPInput/OTPInput.razor.cs

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -54,35 +54,40 @@ private async Task NotifyChangesAsync()
5454

5555
private async Task OnInput(ChangeEventArgs e, int index)
5656
{
57-
Console.WriteLine(">> OnInput called");
58-
var currentValue = otpValues[index] ?? "";
59-
var newValue = new string(e.Value?.ToString()?.Where(char.IsDigit)?.ToArray());
57+
var rawValue = e.Value?.ToString();
58+
var numericValue = new string(rawValue?.Where(char.IsDigit).ToArray());
6059

61-
Console.WriteLine($">> newValue: {newValue}");
62-
if (string.IsNullOrEmpty(newValue))
60+
if (string.IsNullOrEmpty(numericValue))
6361
{
6462
otpValues[index] = string.Empty;
65-
await JSRuntime.InvokeVoidAsync(JsInteropUtils.SetInputElementValue, GetInputId(index), string.Empty);
63+
64+
// Clear the input element if it contained invalid characters
65+
if (!string.IsNullOrEmpty(rawValue))
66+
{
67+
await JSRuntime.InvokeVoidAsync(JsInteropUtils.SetInputElementValue, GetInputId(index), string.Empty);
68+
}
69+
6670
await NotifyChangesAsync();
6771
return;
6872
}
6973

70-
if (int.TryParse(newValue, out var digit))
71-
{
72-
otpValues[index] = digit.ToString();
74+
// If multiple digits were entered (e.g. fast typing or paste), use the last one
75+
var digit = numericValue.Length > 1 ? numericValue[^1].ToString() : numericValue;
7376

74-
if (index < Length - 1)
75-
{
76-
otpValues[index + 1] = string.Empty;
77-
await JSRuntime.InvokeVoidAsync(JsInteropUtils.FocusInputElement, GetInputId(index + 1));
78-
}
77+
otpValues[index] = digit;
78+
79+
// Reset the input value on the client side if it doesn't match the sanitized digit
80+
if (rawValue != digit)
81+
{
82+
await JSRuntime.InvokeVoidAsync(JsInteropUtils.SetInputElementValue, GetInputId(index), digit);
7983
}
80-
else
84+
85+
// Move focus to the next input field
86+
if (index < Length - 1)
8187
{
82-
otpValues[index] = string.Empty;
88+
await JSRuntime.InvokeVoidAsync(JsInteropUtils.FocusInputElement, GetInputId(index + 1));
8389
}
8490

85-
// Notify changes
8691
await NotifyChangesAsync();
8792
}
8893

0 commit comments

Comments
 (0)