如何取消blazor中的onInput事件按键值

How to cancel the onInput event key press value in blazor

我试图在用户开始输入时将 phone 数字格式化为 (###)-###-#### 格式。 我不想在达到长度 14 后接受这些字母。但是,我无法进行此限制。无法将值再次设置回输入控件。我尝试了两个 'value' '@bind-value' 属性。

如果有人能以简单的方式解决这个限制,我将不胜感激。

<input type="text" @bind-value="@PhoneNumber" @oninput="KeyInputHandler" />

@code {

    string phoneNo = string.Empty;

    public string PhoneNumber { get; set; } = string.Empty;

    private void KeyInputHandler(ChangeEventArgs e)
    {
        var key = (string)e.Value;
        if (PhoneNumber.Length < 14)
        {
            PhoneNumber = PhoneNumber.Length switch
            {
                0 => $"({key}",
                3 => $"{key})-",
                8 => $"{key}-",
                _ => $"{key}"
            };
        }
   }

我终于创建了自定义控件,它将数字格式化为 (###) ###-#### 格式。

@using System.Text.RegularExpressions
@inherits InputText
<input @attributes="AdditionalAttributes" 
   class="@CssClass"
   value="@CurrentValue"
   @onkeypress="@OnKeyPressEventHandler"
   @onkeypress:preventDefault
   @onblur="OnBlurEventHandler"
   @oninput="EventCallback.Factory.CreateBinder<string>(this, __value => CurrentValueAsString = __value, CurrentValueAsString)" />

@code {

protected void OnBlurEventHandler(FocusEventArgs e)
{
    if (string.IsNullOrWhiteSpace(CurrentValueAsString))
    {
        return;
    }

    if (!Regex.IsMatch(CurrentValueAsString, @"^\(\d{3}\) \d{3}-\d{4}$"))
    {
        var number = Regex.Replace(CurrentValueAsString, @"[\s()-]", "");
        CurrentValueAsString = Regex.Replace(number, @"(\d{3})(\d{3})(\d{4})", "() -");
    }

    if (CurrentValueAsString.Length > 14)
    {
        CurrentValueAsString = CurrentValueAsString.Substring(0, 14);
    }
}

protected void OnKeyPressEventHandler(KeyboardEventArgs e)
{
    if (string.IsNullOrWhiteSpace(CurrentValueAsString))
    {
        CurrentValueAsString = string.Empty;
    }

    var key = (string)e.Key;
    if (CurrentValueAsString?.Length < 14 && Regex.IsMatch(key, "[0-9]"))
    {
        CurrentValueAsString += CurrentValueAsString.Length switch
        {
            0 => $"({key}",
            3 => $"{key}) ",
            4 => $") {key}",
            5 => $"-{key}",
            8 => $"{key}-",
            9 => $"-{key}",
            _ => $"{key}"
        };
    }
}

}