phone validation in Mvc

Total Post:4

Points:28
 433  View(s)
Ratings:
Rate this:

I want to validate phone no. using data annotation 

 <li class="cell last" style="width: 60%;">

            @Html.TextBoxFor(model => model.PhoneNumber, new { @class = "textbox" }) @Html.ValidationMessageFor(model => model.PhoneNumber)
        </li>
  1. Post:140

    Points:984
    Re: phone validation in Mvc

    hi folks, if you want to validation phone number annotation in MVC.

    use this code which is  shown below:

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

    please check your Models and Views properly:

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

    this Data Annotation alone is  enough if you need regex for validation. as you want to using data annotation so its helpful for you which is shown below:

    Syntax:

    [RegularExpression(@"^([0]|\+91[\-\s]?)?[789]\d{9}$", ErrorMessage = "Your entered Mobile No is not valid.")]

    Code:

    public class PersonModel
    
    {
        [Display(Name = "Mobile Number:")]
        [Required(ErrorMessage = "Mobile Number is required.")]
        [RegularExpression(@"^([0-9]{10})$", ErrorMessage = "Your entered no is Invalid.")]
        public string MobileNumber { get; set; }
    }

    I hope, It will be helpful for you.

    Happy Coding :)

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!