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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With