AspNet MVC Core 2.0 Model validations with custom attribute
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
- A user must 17 years old
- 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.
Date inserted less than 17 years
Date inserted above 100 years
Future Date insert
correct date insert.
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.