Mobile Number Validation in MVC using Data Annotations and Regular Expressions

In this article, we will learn about how to validate mobile number in MVC using Data Annotations and Regular Expressions. You can also learn how to Client Side Password and Confirm Password validation in MVC using Data Annotations 

Model:-


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCCODESOLUTIONS.Models
{


    public class validationsmodel
    {

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

    }
}

Controller(HomeController)

using MVCCODESOLUTIONS.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;

namespace MVCCODESOLUTIONS.Controllers
{
    public class HomeController : Controller
    {

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(validationsmodel MobileNumber)
        {
            return View();
        }

    }
}
View(Index.cshtml)

@model MVCCODESOLUTIONS.Models.validationsmodel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title> Mobile Number Validation in MVC</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }

        .error {
            color: red;
        }
    </style>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", 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>
Out-put:-


Mobile Number Validation in MVC using Data Annotations and Regular Expressions Mobile Number Validation in MVC using Data Annotations and Regular Expressions Reviewed by NEERAJ SRIVASTAVA on 5:00:00 PM Rating: 5

No comments:

Powered by Blogger.