2
@Html.TextBox("MyTextBox", "Value", new {style = "width:250px"})

I have textbox. I want to enter only phone numbers. The format is +1 (_) -___ Total 10 numbers (3+3+4)

How can I do it in Html.Textbox in asp.net mvc?

JJJ
  • 32,902
  • 20
  • 89
  • 102
user2625648
  • 71
  • 1
  • 3
  • 8

2 Answers2

2

There is no way masked Html.Textbox, you can use jquery for this (link) Or you can use DataAnnotation DisplayFormat for this

Community
  • 1
  • 1
Elvin Mammadov
  • 25,329
  • 11
  • 40
  • 82
0

You can use a RegularExpression attribute in your Model like this:

public class MyModel
{
    // The regex maches this pattern: "+1 (xxx) xxx-xxxx" 
    [RegularExpression(@"^\+1 \(\d{3}\) \d{3}-\d{4}$", ErrorMessage = "Invalid Phone Number.")]
    public string PhoneNumber { get; set; }
}

Then, in your View, you'll have:

@Html.TextBoxFor(model => model.PhoneNumber)
@Html.ValidationMessageFor(model => model.PhoneNumber)
ataravati
  • 8,891
  • 9
  • 57
  • 89