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.
Mobile Number Validation in MVC using Data Annotations and Regular Expressions. [Required(ErrorMessage = "Mobile Number is required.")] [RegularExpression(@"^([0-9]{10})$", ErrorMessage = "Please Enter Valid Mobile Number.")]
There are different ways to validate phone numbers in C#. You can use Regex or the libphonenumber-csharp library to validate phone number format and ensure proper phone number input. Also, you can utilize a phone number validation API.
Mobile Number validation criteria: The first digit should contain number between 7 to 9. The rest 9 digit can contain any number between 0 to 9. The mobile number can have 11 digits also by including 0 at the starting. The mobile number can be of 12 digits also by including 91 at the starting.
Phone number validation uses the DataAnnotations namespace, which has two validation attributes: DataType and Phone. You should use the DataType in your model class if your MobilePhone field is of a simple type.
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)
Try for simple regular expression for Mobile No
[Required (ErrorMessage="Required")]
[RegularExpression(@"^(\d{10})$", ErrorMessage = "Wrong mobile")]
public string Mobile { get; set; }
You don't have a validator on the page. Add something like this to show the validation message.
@Html.ValidationMessageFor(model => model.PhoneNumber, "", new { @class = "text-danger" })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With