Conditional Validation in ASP.NET MVC ( RequiredIf )

Conditional Validation in ASP.NET MVC ( RequiredIf )


In this article, we will discuss custom validation attribute named "RequiredIf" with an example in ASP.NET MVC.


- Open Visual Studio and create a new project.


- Select the "ASP.NET Web Application (.NET Framework) C#" option.


RequiredIfASPNETMVC_1.PNG

RequiredIfASPNETMVC_2.PNG

- Right-click on Models folder, choose "Add", then choose the class. Name it as Employee.cs.


using System;
using System.ComponentModel.DataAnnotations;
using WebApplication1.CustomValidation;

namespace WebApplication1.Models
{
    public class Employee
    {
        public int ID { get; set; }

        [Required(ErrorMessage = "Please Enter Name")]
        public string Name { get; set; }

        [Required(ErrorMessage = "Please Enter Title")]
        public string Title { get; set; }

        [Required(ErrorMessage = "Please Enter Department")]
        public int Department { get; set; }

        [Required(ErrorMessage = "Please Enter Hire Date")]
        [Display(Name = "Hire Date")]
        [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
        public DateTime HireDate { get; set; }

        [RequiredIf("Department", (int)DepartmentName.IT, ErrorMessage = "Please Enter Salary")]
        public int? Salary { get; set; }
    }

    public enum DepartmentName
    {
        Marketing = 1,
        HumanResources = 2,
        IT = 3,
        Sales = 4
    }
}

- Right-click on the project and select “Add Folder”, name it CustomValidation, and add class with name RequiredIfAttribute. Then, write the following code in it.


using System.ComponentModel.DataAnnotations;

namespace WebApplication1.CustomValidation
{
    public class RequiredIfAttribute : ValidationAttribute
    {
        public string PropertyName { get; set; }
        public object Value { get; set; }

        public RequiredIfAttribute(string propertyName, object value, string errorMessage = "")
        {
            PropertyName = propertyName;
            ErrorMessage = errorMessage;
            Value = value;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var instance = validationContext.ObjectInstance;
            var type = instance.GetType();
            var proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
            if (proprtyvalue.ToString() == Value.ToString() && value == null)
            {
                return new ValidationResult(ErrorMessage);
            }
            return ValidationResult.Success;
        }
    }
}

- Open the HomeController class and write the following code in it.

    public class HomeController : Controller
    {
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(Employee employee)
        {
            if (ModelState.IsValid)
            {
                RedirectToAction("Index");
            }

            return View();
        }
		
		...

- Right-click on Index method in HomeController. The "Go to View" window will appear with the default index. Here, click on "Go to View".


RequiredIfASPNETMVC_3.PNG

@model WebApplication1.Models.Employee
@using WebApplication1.Models
@{
    ViewBag.Title = "Index";
}

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Create Employee</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name)
            </div>
        </div>

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

        <div class="form-group">
            @Html.LabelFor(model => model.Department, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.Department,
                    new SelectList(
                        new List<SelectListItem>
                        {
                            new SelectListItem { Text = "Marketing", Value = ((int)DepartmentName.Marketing).ToString()},
                            new SelectListItem { Text = "Human Resources", Value = ((int)DepartmentName.HumanResources).ToString()},
                            new SelectListItem { Text = "IT", Value = ((int)DepartmentName.IT).ToString()},
                            new SelectListItem { Text = "Sales", Value = ((int)DepartmentName.Sales).ToString()},
                        }, "Value", "Text"),
                    "Select Department",
                    new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.Department)
            </div>
        </div>

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

        <div class="form-group">
            @Html.LabelFor(model => model.Salary, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Salary, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Salary)
            </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>
}

- Build and run the project by pressing CTRL + F5.


RequiredIfASPNETMVC_4.PNG

RequiredIfASPNETMVC_5.PNG

RequiredIfASPNETMVC_6.PNG

tag : Required if in asp.net mvc 5,required conditional in asp.net mvc,conditional validation in asp.net mvc,custom validation required in asp.net mvc