dataannotations example in mvc

Updated : Feb 08, 2020 in Articles

Data annotations and validations in MVC with example

In this article, we will learn about how to validate the form by using Data annotations in MVC with example

ASP.NET MVC applications Validation is an important aspect. Validation is used to check whether the user input is valid or not. ASP.NET MVC provides a set of validations that is easy to use and powerful way to check for errors, if necessary to display messages to the users.

In this article, we will add data annotations to our model class(UserDetails.cs), Asp.net MVC provides to us with some built-in set of validation attributes that can be applied to any model class directly in your application, such as Required, StringLength, RegularExpression, Custom Implementing, and Range validation attributes.

go to visual studio select asp.net web Application and enter your project name =>ok

Create Visual studio Prject

choose MVC application =>ok

Create Visual studio Prject

Create model class name like UserDetails following the given below c# snippet code

bind JSON data to kendo grid in MVC

Data annotations contain formatting attributes such as DataType that help with formatting. The validation attributes specify behavior that you want to enforce on the model properties they are applied to.

Required and MinimumLength attributes: this attributes indicates that a property must have a value, but nothing prevents entering white space

RegularExpression attribute: this attribute is used to limit what characters can be input.

 public class UserDetails
    {
        public int ID { get; set; }

        [Required]
        [Display(Name ="First Name")]
        public string FirstName { get; set; }

        [Display(Name ="Last Name")]
        [NotEqualTo("FirstName", ErrorMessage ="Last name can not be same as first name!")]
        public string LastName { get; set; }

        [Range(18, 60, ErrorMessage="Age must be over 18 and under 60")]
        public int Age { get; set; }

        [Display(Name ="Birth Month")]
        public string BirthMonth { get; set; }

        public static IEnumerable<SelectListItem> Months
        {
            get
            {
                return DateTimeFormatInfo
                       .InvariantInfo
                       .MonthNames
                       .Where(m=> !string.IsNullOrEmpty(m))
                       .Select((monthName, index) => new SelectListItem
                       {
                           Value = (index + 1).ToString(),
                           Text = monthName
                       });
            }
        }

        [DataType(DataType.PhoneNumber)]
        [RegularExpression("\\d{9}",ErrorMessage ="Please enter a 9-digit number without spaces")]
        [Display(Name ="Phone Number")]
        public long PhoneNum { get; set; }

        [Required]
        [DataType(DataType.EmailAddress, ErrorMessage ="Not a valid e-mail address")]
        public string Email { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [StringLength(Int32.MaxValue, MinimumLength = 8,ErrorMessage ="Password must be mminimum {2} characters long")]
        public string Password { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name ="Confirm Password")]
        [System.ComponentModel.DataAnnotations.Compare("Password",ErrorMessage ="Must match Password")]
        //[EqualTo("Password", ErrorMessage = "Password does not match Confirm Password")]
        public string ConfirmPassword { get; set; }
    }

Create a controller name like home and implement the action method name like index see the following given below code

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

right-click on the action method generate a view using scaffolding see the given below HTML page

@using Validations.Models
@model Validations.Models.UserDetails

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>


@using (Html.BeginForm("AddUser","Home")) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>UserDetails</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.BirthMonth, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.BirthMonth, UserDetails.Months, "Please select a month", new {@class="form-control"})
                @Html.ValidationMessageFor(model => model.BirthMonth, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.PhoneNum, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PhoneNum, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.PhoneNum, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.PasswordFor(model => model.Password, new { @class = "form-control", placeholder="Enter password" })
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.PasswordFor(model => model.ConfirmPassword, new { @class = "form-control", placeholder="Confirm Password" })
                @Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

try to run your application see the given below output

data annotations in asp.net mvc

Santosh Tiwari
Like
Like Love Haha Wow Sad Angry