Hi @Anjali Agarwal
I want to show the validation for age on my cshtml page. If someone DOB shows that he/she is less than 18 compare to current date then I need to show the validation saying "you should be at least 18 years old".
You can try to create a custom attribute to validate the date.
Refer to the following steps and code:
Create a CustomValidation folder in your project and add Min18Years class with the following code:
//using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
//using System.ComponentModel.DataAnnotations;
public class Min18Years : ValidationAttribute, IClientModelValidator
{
//server side validation
protected override ValidationResult? IsValid(object value, ValidationContext validationContext)
{
var employee = (EmployeeInfoViewModel)validationContext.ObjectInstance;
if (employee.DateOfBirth == null)
return new ValidationResult("Date of Birth is required.");
var age = DateTime.Today.Year - DateTime.Parse(employee.DateOfBirth).Year;
return (age >= 18) ? ValidationResult.Success : new ValidationResult("Employee should be at least 18 years old.");
}
//client side validation
public void AddValidation(ClientModelValidationContext context)
{
context.Attributes.Add("data-val-dateofbirth", "Invalid date, Employee should be at least 18 years old.");
}
}
Add the [Min18Years]
on the DateOfBirth
property.
//using System.ComponentModel.DataAnnotations;
//using WebApplication3.CustomValidation;
public class EmployeeInfoViewModel
{
[DisplayName("Last Name")]
public string LastName { get; set; } = null!;
[DisplayName("First Name")]
[Required]
public string FirstName { get; set; } = null!;
[DisplayName("Middle Name")]
public string? MiddleName { get; set; }
[Min18Years]
public string DateOfBirth { get; set; } = null!;
}
Then, in the view page, add the client-side validation:
@model WebApplication3.Models.EmployeeInfoViewModel
<div class="row">
<div class="col-md-4">
<form asp-action="CreateEmployee">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="LastName" class="control-label"></label>
<input asp-for="LastName" class="form-control" />
<span asp-validation-for="LastName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="FirstName" class="control-label"></label>
<input asp-for="FirstName" class="form-control" />
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="MiddleName" class="control-label"></label>
<input asp-for="MiddleName" class="form-control" />
<span asp-validation-for="MiddleName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="DateOfBirth" class="control-label"></label>
<input asp-for="DateOfBirth" class="form-control" />
<span asp-validation-for="DateOfBirth" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$.validator.addMethod('dateofbirth', function (value, element, params) {
var date = $(element).val();
if (date != null) { //365 * 24 * 60 * 60 * 1000 = 31536000000
return Math.floor((new Date() - new Date(date)) / 31536000000) >= 18;
}
return false;
});
$.validator.unobtrusive.adapters.add('dateofbirth', function (options) {
var element = $(options.form).find('#DateOfBirth');
options.rules['dateofbirth'] = [element];
options.messages['dateofbirth'] = options.message;
});
</script>
}
The result as below:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion