ttmind

Main Navigation

ttmind
  • jim-jams
  • Tech
  • Positive
Login

Login

Facebook Google

OR

Remember me Forgot password?

Don't have account? Signup here.

Sort by Categorys

.Net

PHP

Java

JavaScript

Database

Server

Client Side

Tools

Artificial Intelligence

Cloud

Hybrid Development

Event

Smart City

Education

Security

Scrum

Digital Marketing

APP Development

Business

Internet

Simulation

Art

Network

Microservices

Architecture

Technology

Leadership

    Top Articles

  • How Does Social Media Bring People Together?
    TTMind Author
  • How to read appSettings JSON from Class Library in ASP.NET Core
    Anil Shrestha
  • Printing Support In Asp.Net Core
    TTMind Author
  • HOW TO EXTRACT TEXT FROM IMAGE USING JAVASCRIPT (OCR with Tesseract.js)?
    Prakash Pokhrel
  • Images Upload REST API using ASP.NET Core
    Prakash Pokhrel
  • Related Topic

  • How to read appSettings JSON from Class Library in ASP.NET Core
  • Printing Support In Asp.Net Core
  • Images Upload REST API using ASP.NET Core
  • How to use IActionFilter, IAsyncActionFilter in ASP.NET Core MVC?
  • ASP.NET CORE - Blazor CRUD operation using ADO.NET
  • Tech
  • About Us
  • Contact Us
  • TechHelp
  • PositiveHelp
  • Jim-Jams Help
  • Terms & Conditions

© Copyright ttmind.com

Main Content

AspNet MVC Core 2.0 Model validations with custom attribute

.Net .Net Core about 7 years ago || 9/22/2018 || 4.2 K View

  • Hide

How to make the custom validation attribute in aspnet mvc core 2.0?

.Net framework provides us to make our own custom validation attribute by inherit “ValidationAttribute” using namespace “System.ComponentModel.DataAnnotations.”

We need to validate the data before we store in a database. So, we have our own logic which framework did not provide.  For example, we have to valid date of birth of user, our condition be like

  1. A user must 17 years old
  2. Date of birth cannot be an upcoming date or not more than 100 years old.
namespace myfrom.CustomeValidation
{

    public class ValidAge : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var model = validationContext.ObjectInstance as FormModel;

            var db = model.DOB.AddYears(100);

            if (model == null)
                throw new ArgumentException("Attribute not applied on Model");

            if (model.DOB > DateTime.Now.Date)
                return new ValidationResult($"{validationContext.DisplayName} can't be in future");
            if (model.DOB > DateTime.Now.Date.AddYears(-16))
                  return new ValidationResult("You must be 17 years old.");
            if (db < DateTime.Now.Date)
                return new ValidationResult("We rescept you but we cannot accept this date. over 100 years old.");
            return ValidationResult.Success;
        }
    }

}

 We Create the custom validation attribute, let apply on our model. And test on it.

public class FormModel
  {
        [Required, Display(Name = "Date of Birth")]
        [ValidAge] // we create our own validation attribute
        [DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
        public DateTime DOB { get; set; }
  }

No we create the form in aspnet core mvc.

<form method="post" asp-controller="form" asp-action="insert">
  <div class="form-group">
            <label asp-for="DOB"></label>
            <input asp-for="DOB" class="form-control">
            <span asp-validation-for="DOB"></span>
     </div>
    <div class="form-group col-lg-12">
        <button type="submit" class="btn btn-primary">Submit</button>
    </div>
 </form>

Tested Result is below.

When first-time view load.

AspNet MVC Core 2.0 Model validations with costume attribute

Date inserted less than 17 years

AspNet MVC Core 2.0 Model validations with costume attribute

Date inserted above 100 years 

AspNet MVC Core 2.0 Model validations with costume attribute

Future Date insert

AspNet MVC Core 2.0 Model validations with costume attribute

correct date insert.

AspNet MVC Core 2.0 Model validations with costume attribute

We cannot trust fully on client-side validation but we have to validate data also in client side for user better experience. We always need to validate the data in a server side. If you have any question please leave a comment. on it. You also can see this code on GitHub  you can see crud operation in aspnet  mvc core 2.0 click on this  link 

I hope I can help you with this article please share with your friend, team member.

 

  • 2
  • 0
  • 0
    • Facebook
    • Twitter
    • Google +
    • LinkedIn

About author

Anil Shrestha

Anil Shrestha

Qualified and skilled professional with experience working as a Software Developer

Reset Your Password
Enter your email address that you used to register. We'll send you an email with your username and a link to reset your password.

Quick Survey