Sunday, 29 October 2017

Mobile Number (Cellphone Number) Validation using Data Annotations and RegularExpressions (Regex) in ASP.Net MVC

Mobile Number (Cellphone Number) Validation using Data Annotations and RegularExpressions (Regex) in ASP.Net MVC
Description:


In this example we explain that how perform Mobile Number validation using Data Annotation in Asp.Net MVC.or Cell Phone Number validation using Data Annotations and Regular Expression in Asp.Net MVC.or regular expression in MVC to validate the Mobile Number or Phone Number in Razor view. Or Mobile Phone Number validation for 10 digits’ number using Data Annotations or Regular Expression in MVC Razor.

Model:

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

Controller:

public class EmployeeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(EmployeeModel employee)
        {
            return View();
        }
    }

View: 

@model MobileNumber_Validation_MVC.Models.PersonModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
      <title>Mobile Number (Cellphone Number) Validation using Data Annotations and RegularExpressions (Regex) in ASP.Net MVC</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }
        .error {
            color: red;
        }
    </style>
</head>
<body>
    @using (Html.BeginForm("Index", "Employee", FormMethod.Post))
    {
        <table>
            <tr>
                <td>@Html.LabelFor(m => m.MobileNumber)</td>
                <td>@Html.TextBoxFor(m => m.MobileNumber)</td>
                <td>@Html.ValidationMessageFor(m => m.MobileNumber, "", new { @class = "error" })</td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="Submit"/></td>
                <td></td>
            </tr>
        </table>
    }
</body>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
</html>


This entry was posted in :

0 comments:

Post a Comment