简体   繁体   English

格式化字符串电话号码MVC Razor而不解析为十进制

[英]Format string phone number MVC Razor without parsing to decimal

I am trying to format phone numbers that are being looped in from my viewModel like so: (###) ###-#### without having to parse the string to a decimal. 我正在尝试格式化从我的viewModel循环的电话号码,如下所示: (###) ###-####而不必将字符串解析为小数。

This method gives a Formatting is specified, but argument is not IFormattable error: 此方法Formatting is specified, but argument is not IFormattableFormatting is specified, but argument is not IFormattable错误:

@foreach (var client in Model.Clients)
{
    <td>@String.Format("{0:(###) ###-####}", client.TelephoneNumber)</td>
}

So, I would need to parse to a decimal: 所以,我需要解析为小数:

@foreach (var client in Model.Clients)
{
    <td>@String.Format("{0:(###) ###-####}", Decimal.Parse(client.TelephoneNumber))</td>
}

But there is no guarantee that the numbers being looped in will be just digits so most likely at least one parse attempt will fail. 但是无法保证循环的数字只是数字,因此最有可能至少一次解析尝试失败。

Is there a way to achieve this formatting without the need to Parse to a decimal? 有没有办法实现这种格式,而无需解析为小数?

If your TelephoneNumber is a string you always can use substrings to format number. 如果您的TelephoneNumber是一个string您始终可以使用子字符串格式化数字。 It's not so clean, but you don't need any separate libraries and convert to decimal : 它不是那么干净,但你不需要任何单独的库并转换为decimal

        @String.Format("({0}) {1}-{2}"
            , client.TelephoneNumber.Substring(0, 3)
            , client.TelephoneNumber.Substring(3, 3)
            , client.TelephoneNumber.Substring(6, client.TelephoneNumber.Length - 6))

Try this, you may put it in a static function somewhere for repeated use. 试试这个,你可以把它放在某个地方的静态函数中重复使用。

var match = Regex.Match("1231231234", @"(\d{3})(\d{3})(\d{4})");
Console.WriteLine( "(" + match.Groups[1] + ") " + match.Groups[2] + "-" + match.Groups[3]);

Or even easier if you are only dealing with 10 digit phone numbers: 如果您只处理10位数的电话号码,甚至更容易:

Regex.Replace(phoneNum, @"(\d{3})(\d{3})(\d{4})", "($1) $2-$3");

Read-Only 只读

If you're only interested in displaying the phone number, you could make it an HTML helper like this: 如果您只对显示电话号码感兴趣,可以将其设为HTML帮助:

public static MvcHtmlString FormatPhoneNum(this HtmlHelper helper, string phoneNum)
{
    //You could strip non-digits here to make it more robust

    if (String.IsNullOrEmpty(phoneNum)) return phoneNum;

    return new MvcHtmlString(Regex.Replace(phoneNum, @"(\d{3})(\d{3})(\d{4})", "($1) $2-$3"));  //US Phone Number
}

And then use like this: 然后像这样使用:

@foreach (var client in Model.Clients)
{
    <td>@Html.FormatPhoneNumber(client.TelephoneNumber)</td>
}

Editing 编辑

If you also need to edit the phone number and want to display it formatted in the editor textbox, you can create a wrapper property on your view model to transform the phone number: 如果您还需要编辑电话号码并希望在编辑器文本框中显示格式,则可以在视图模型上创建包装器属性以转换电话号码:

public class Client
{
    public string TelephoneNumber {get; set;}

    //Require 10 digits, each surrounded by any non-digit characters (will strip all non-digits)
    [RegularExpression(@"(\D*\d\D*){10}", ErrorMessage = "Please enter a 10 digit phone number")]
    public string FormattedPhoneNum
    {
        get
        {
            MyHelpers.FormatPhoneNumber(TelephoneNumber);
        }
        set
        {
            TelephoneNumber = MyHelpers.StripPhoneNumber(value);
        }
    }
}

public class MyHelpers
{
    public static StripPhoneNumber(string phone)
    {
        if (phone == null)
            return phone;
        else
            return _nonDigits.Replace(phone, String.Empty);
    }

    public static string FormatPhoneNumber(string phoneNum)
    {
        phoneNum = StripPhoneNumber(phoneNum);

        if (String.IsNullOrEmpty(phoneNum)) return phoneNum;

        return Regex.Replace(phoneNum, @"(\d{3})(\d{3})(\d{4})", "($1) $2-$3");  //US Phone Number
    }
}

Note the RegularExpressionAttribute on the property. 请注意属性上的RegularExpressionAttribute。 It takes a very lenient stance on user input. 对用户输入采取非常宽松的立场。 It is satisfied as long as the user enters at least 10 digits into the textbox regardless of any other characters typed in. You might need to make this more restrictive for your own purposes. 只要用户在文本框中输入至少10位数字而不管输入的其他任何字符,都会感到满意。您可能需要根据自己的需要对此进行更严格的限制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM