C# 如何将电话号码格式设置为0000-0000
我想向用户显示0000-0000格式的电话号码,我的型号是C# 如何将电话号码格式设置为0000-0000,c#,asp.net,razor,C#,Asp.net,Razor,我想向用户显示0000-0000格式的电话号码,我的型号是 [DisplayName("Phone number")] [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:0000-0000}")] [Required(ErrorMessage = "*Required")] public string Phone{ set; get; } = string.Empty; 观点是这样的 <div clas
[DisplayName("Phone number")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:0000-0000}")]
[Required(ErrorMessage = "*Required")]
public string Phone{ set; get; } = string.Empty;
观点是这样的
<div class="form-group">
@Html.LabelFor(model => model.Phone, htmlAttributes: new { @class = "control-label col-md-4"})
<div class="col-md-8">
@Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })
</div>
</div>
@LabelFor(model=>model.Phone,htmlAttributes:new{@class=“controllabel col-md-4”})
@EditorFor(model=>model.Phone,new{htmlAttributes=new{@class=“form control”})
@Html.ValidationMessageFor(model=>model.Phone,“,new{@class=“text danger”})
但是不起作用,我将向您的帮助说明您可以为您需要的电话号码格式指定一个
regex
:
[DisplayName("Phone number")]
[Required(ErrorMessage = "*Required")]
[RegularExpression("^\d{4}-\d{4}$", ErrorMessage = "Please enter valid phone no.")]
public string Phone{ set; get; } = string.Empty;
这将始终确保您的电话号码在验证期间的格式为0000-0000
要将手机格式化为所需格式,请从属性中删除DisplayFormat
属性,然后您可以使用TextBoxFor
的重载,如下所示:
@Html.TextBoxFor(model => model.Phone,"{0:####-####}", new { htmlAttributes = new { @class = "form-control" } })
通常,DataFormatString将用于将非字符串类型(int、date等)格式化为特定的字符串格式,而不是重新格式化现有字符串。您应该在视图中设置字符串格式。如果您提供razor视图代码,我们可以提供帮助。0000-0000是什么类型的电话格式?这是特定国家的一部分吗?是的,它是特定国家的一种格式