Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core - Custom model validation

Tags:

In MVC when we post a model to an action we do the following in order to validate the model against the data annotation of that model:

if (ModelState.IsValid) 

If we mark a property as [Required], the ModelState.IsValid will validate that property if contains a value or not.

My question: How can I manually build and run custom validator?

P.S. I am talking about backend validator only.

like image 269
user2818430 Avatar asked Oct 11 '17 18:10

user2818430


People also ask

What is model validation in asp net core?

Validation attributes let us specify validation rules for model properties. Model state represents errors that come from two sub systems' model binding and model validation. There are in-built attributes in ASP.NET MVC core, Attribute.

How can we use custom model binder in asp net core?

Model binding allows controller actions to work directly with model types (passed in as method arguments), rather than HTTP requests. Mapping between incoming request data and application models is handled by model binders.

What is ModelState in asp net core?

Model state represents errors that come from two subsystems: model binding and model validation. Errors that originate from model binding are generally data conversion errors. For example, an "x" is entered in an integer field.


1 Answers

In .NET Core, you can simply create a class that inherits from ValidationAttribute. You can see the full details in the ASP.NET Core MVC Docs.

Here's the example taken straight from the docs:

public class ClassicMovieAttribute : ValidationAttribute {     private int _year;      public ClassicMovieAttribute(int Year)     {         _year = Year;     }      protected override ValidationResult IsValid(object value, ValidationContext validationContext)     {         Movie movie = (Movie)validationContext.ObjectInstance;          if (movie.Genre == Genre.Classic && movie.ReleaseDate.Year > _year)         {             return new ValidationResult(GetErrorMessage());         }          return ValidationResult.Success;     } } 

I've adapted the example to exclude client-side validation, as requested in your question.

In order to use this new attribute (again, taken from the docs), you need to add it to the relevant field:

[ClassicMovie(1960)] [DataType(DataType.Date)] public DateTime ReleaseDate { get; set; } 

Here's another, simpler example for ensuring that a value is true:

public class EnforceTrueAttribute : ValidationAttribute {     public EnforceTrueAttribute()         : base("The {0} field must be true.") { }      public override bool IsValid(object value) =>         value is bool valueAsBool && valueAsBool; } 

This is applied in the same way:

[EnforceTrue] public bool ThisShouldBeTrue { get; set; } 

Edit: Front-End Code as requested:

<div asp-validation-summary="All" class="text-danger"></div> 

The options are All, ModelOnly or None.

like image 195
Kirk Larkin Avatar answered Sep 21 '22 19:09

Kirk Larkin