Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

c# - Phone Number Validation MVC

I am trying to use a regular expression to validate a phone number and return an error when an invalid number or phone number is submitted.

MVC Code:

<ol class="row">
    <li class="cell" style="width: 20%;">Phone Number:</li>
    <li class="cell last" style="width: 60%;">
        @Html.TextBoxFor(model => model.PhoneNumber, new { @class = "textbox" }) 
        @Html.ValidationMessageFor(model => model.PhoneNumber)
    </li>
</ol>

C# Code:

[DataType(DataType.PhoneNumber)]
[Display(Name = "Phone Number")]
[Required(ErrorMessage = "Phone Number Required!")]
[RegularExpression(@"^(?([0-9]{3}))?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$",
                   ErrorMessage = "Entered phone format is not valid.")]
public string PhoneNumber { get; set; }

However, the input box will not show a message to the user indicating that the phone number which was submitted is not valid.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Model

[Required(ErrorMessage = "You must provide a phone number")]
[Display(Name = "Home Phone")]
[DataType(DataType.PhoneNumber)]
[RegularExpression(@"^(?([0-9]{3}))?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid phone number")]
public string PhoneNumber { get; set; }

View:

@Html.LabelFor(model => model.PhoneNumber)
@Html.EditorFor(model => model.PhoneNumber)
@Html.ValidationMessageFor(model => model.PhoneNumber)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...