Updated March 30, 2023
Introduction to ASP.NET MVC Validation
ASP.NET MVC Validation is the important aspect; Validation is the essential thing in MVC it is used to check whether the valid input from the user. In ASP.NET MVC offers a set of validations that is easy to make use of it and it also provides the displaying of error messages to the user for easy understanding.
Using Attributes ASP.NET MVC Validation
In ASP.NET MVC Validation there will be a Model validation process that is used to check whether the given user input is right for Model Binding and also there will be an error message display. Initially, it checks whether valid entries are made, while checking the user input it checks for suitable data to inform the user about invalid data and it helps out to enter the valid data with the expected form through displaying the messages. In ASP.NET MVC Validation there will be various attributes, let’s see the attributes available in the MVC Validations,
There are different types of attributes available in the ASP.NET MVC Model Validation which is used to build to validate at the client-side, let’s see a few validation attributes which applied to the property model with examples as follows,
• Required – this attribute is used to set for the mandatory fields. For Example [Required(ErrorMessage = “Required User FirstName”)]
• DataType- this attribute is used to set the type of data
• StringLength- this attribute is used to set the character limitation. For example [StringLength(20, MinimumLength = 4, ErrorMessage = “Must be 4-Character Long”)]
• Range(min,max)- this attribute is used to set the maximum and minimum numbers
• Compare- this attribute is used to compare the properties of two same names it is essentially used for Confirm Password. For Example
[Compare (“ConfirmPassword”, ErrorMessage = “Confirm Password and Password must be same”)]
public string Password { get; set; }
• RegularExpression- this attribute is used to specify the pattern matching which is mainly used for email address. For Example,
[RegularExpression(@”\w+([-+.’]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*”)]
public string E-mail_ID { get; set; }
• Custom Validation- this attribute is used for the programmer own logical validation of the model property.
Let’s see one sample programming example,
Employee Model Class
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using ValidationAttribute_Sample.Validation;
namespace Mvc_ValidationAttribute
{
public class Employee_Model
{
public int User_Id { get; set; }
[Required(ErrorMessage = "Name is must")]
public string UserName { get; set; }
[Required(ErrorMessage = "Designation is must")]
public string Position { get; set; }
[Required(ErrorMessage = "Office name must")]
public string Office { get; set; }
[Required(ErrorMessage = "Hired-Date is must")]
[Display(Name = "Hire Date")]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
[CustomHireDate(ErrorMessage = "Date should be less than or equal to Today's Date")]
public DateTime HireDate { get; set; }
[Required(ErrorMessage = "Salary is must")]
public int Salary { get; set; }
}
}
Let’s see one custom validation code, just right click on the project and include the new folder and give the suitable name and add the class with HireDate_Customer and include the following code,
Custom Validation Code for HireDate
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using Mvc_CustomValidation_Demo.CustomValidation;
namespace Mvc_CustomValidation
{
public class HireDate_CustomValidation : ValidationAttribute
{
public override bool IsValid(object value)
{
DateTime dateTime = Convert.ToDateTime(value);
return dateTime <= DateTime.Now;
}
}
}
ASP.NET MVC Validation Model
Model validation is the process in MVC ASP.NET where it is used to check whether the specified user input is accurate for Model Binding and also there will be an error message display. In the beginning, it checks whether the entered data are valid, while checking the user input it checks for suitable data to inform the user about invalid data and it also helps to enter the valid data with the expected form through displaying the messages.
Example
In this validation model let’s see one sample program which validates the user input with the help of annotations. To add a controller with the name of StudentController and then add the StudentModel Class.
Student_Controller.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Mvc_Validations_App.Controllers
{
public class StudentController : Controller
{
// GET: Students
public ActionResult Index()
{
return View();
}
}
}
Student_Model_Class.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using MvcCustomValidationAttribute_Demo.CustomValidation;
namespace MvcValidationAttribute
{
public class Student
{
public int ID { get; set; }
[Required(ErrorMessage ="User Name is required")]
[MaxLength(12)]
public string Name { get; set; }
[Required(ErrorMessage ="Email is required")]
[EmailAddress(ErrorMessage = "Please enter valid Email Address")]
public string Email { get; set; }
[Required(ErrorMessage = "Contact is required")]
[DataType(DataType.PhoneNumber)]
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Invalid Phone number")]
public string Contact { get; set; }
}
}
Index.cshtml (View Page)
@model MvcApplicationDemo.Models.Student
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Student</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, "", 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.Contact, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Contact, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Contact, "", 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")
}
Let’s see the following output as shown below
In this validation form we can able to see that it validates the form fields and if any invalid data entered the error messages will be displayed.
Conclusion
In this article, we have learned about the ASP.NET MVC Validations and their various attributes with the model validations. In MVC Validation Model Validation is required for data integrity to ensure the entered user data is valid. Hope the article is helpful to understand.
Recommended Articles
We hope that this EDUCBA information on “ASP.NET MVC Validation” was beneficial to you. You can view EDUCBA’s recommended articles for more information.