I'm trying to format the phone numbers to (###)-###-#### format as the user starts typing. I do not want to accept the letters after reaching the length 14. However, I'm unable to make this restriction. Not able to set the value back again to the input control. I tried with both 'value' '@bind-value' attributes.
I would appreciate it if anyone figures out this restriction in a simple way.
<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}"
};
}
}
I finally created custom control which formats the number in (###) ###-#### format.
@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}"
};
}
}
}