2

当用户开始输入时,我正在尝试将电话号码格式化为 (###)-###-#### 格式。我不想在达到长度 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}"
            };
        }
   }

4

1 回答 1

0

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

@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})", "($1) $2-$3");
    }

    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}"
        };
    }
}

}

于 2020-04-22T22:44:43.630 回答