Making a control required on the cshtml page

Anjali Agarwal 1,426 Reputation points
2023-02-08T23:40:41.31+00:00

I have the following Model class

    
public partial class EmployeeInfo
{ 
    [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; }


    public string DateOfBirth { get; set; } = null!;
   
    
}

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". this is how my view looks like:


@model AckPackage.Models.EmployeeInfo
@{
    ViewData["Title"] = "Create";
}


 <div class="form-group row">
                <div class="col-sm-4">
                    <label asp-for="DateOfBirth" class="control-label"></label>
                    <input asp-for="DateOfBirth" class="form-control input-lg" type="date" />
                    <span asp-validation-for="DateOfBirth" class="text-danger"></span>
                </div>/div>

How can I accomplish validation of this type.
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,530 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,463 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,863 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Zhi Lv - MSFT 32,316 Reputation points Microsoft Vendor
    2023-02-09T05:45:00.4666667+00:00

    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:

    image1


    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

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.