Custom Validation Attributes: Comparing two properties in the same model

前端 未结 7 448
谎友^
谎友^ 2020-12-01 06:39

Is there a way to create a custom attribute in ASP.NET Core to validate if one date property is less than other date property in a model using ValidationAttribute<

7条回答
  •  余生分开走
    2020-12-01 07:03

    I created a library with the most common custom validations in ASP.NET Core. The library also has the client-side validation for all the server-side custom validations. The library solves OP's problem with a single attribute as follows:

    // If you want the StartDate to be smaller than the EndDate:
    [CompareTo(nameof(EndDate), ComparisionType.SmallerThan)] 
    public DateTime StartDate { get; set; }
    

    Here is the GitHub link of the library: AspNetCore.CustomValidation

    Currently, the library contains the following validation attributes:

    1. FileAttribute - To validate file type, file max size, file min size;

    2. MaxAgeAttribute - To validate maximum age against date of birth value of DateTime type;

    3. MinAgeAttribute - To validate minimum required age against a date of birth value of DateTime type;

    4. MaxDateAttribute -To set max value validation for a DateTime field;

    5. MinDateAttribute - To set min value validation for a DateTime field;

    6. CompareToAttibute – To compare one property value against another property value;

    7. TinyMceRequiredAttribute -To enforce required validation attribute on the online text editors like TinyMCE, CkEditor, etc.

提交回复
热议问题