[英]Format number in US Phone number format while typing in the Editor
Have a phone number textbox, it has to be formatted like US phone number format on the go. 有一个电话号码文本框,必须随时随地像美国电话号码格式一样进行格式化。
If a single character typed, let say 9 如果键入单个字符,则说9
In this case it should be displayed as 9 在这种情况下,应显示为9
Next 8 is typed and it should be displayed as 98 键入下一个8,应显示为98
Next 9 is typed and it should be displayed as 989- 输入下一个9,它应该显示为989-
Next 1 is typed and it should be displayed as 989-1 键入下一个1,它应显示为989-1
Like wise it should be format the 10 digits. 同样,它应该设置10位数字的格式。
Format : ###-###-####
格式:
###-###-####
I got some help but it was used to format after complete typing the 10 digits. 我得到了一些帮助,但是在完全输入10位数字后就被用来格式化了。 Used Regex format and ToString() formatting.
使用Regex格式和ToString()格式。
public static string formatPhoneNumber(string phoneNum, string phoneFormat)
{
//phoneNum = " 12";
if (phoneFormat == "")
{
// If phone format is empty, code will use default format (###) ###-####
phoneFormat = "###-###-####";
}
// First, remove everything except of numbers
Regex regexObj = new Regex(@"[^\d]");
phoneNum = regexObj.Replace(phoneNum, "");
// Second, format numbers to phone string
if (phoneNum.Length > 0)
{
phoneNum = Convert.ToInt64(phoneNum).ToString(phoneFormat);
}
return phoneNum;
}
Using the text changed event and calling this method to format the text every text change. 使用文本更改事件并调用此方法以在每次文本更改时设置文本格式。
private string PhoneNumberFormatter(string value)
{
value = new Regex(@"\D").Replace(value, string.Empty);
if (value.Length > 3 & value.Length < 7)
{
value = string.Format("{0}-{1}", value.Substring(0, 3), value.Substring(3, value.Length - 3));
return value;
}
if (value.Length > 6 & value.Length < 11)
{
value = string.Format("{0}-{1}-{2}", value.Substring(0, 3), value.Substring(3, 3), value.Substring(6));
return value;
}
if (value.Length > 10)
{
value = value.Remove(value.Length - 1, 1);
value = string.Format("{0}-{1}-{2}", value.Substring(0, 3), value.Substring(3, 3), value.Substring(6));
return value;
}
return value;
}
With the above method, my requirement is fulfilled but if any optimized way is there please let me know. 使用上述方法,可以满足我的要求,但是如果有任何优化的方法,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.