Greater Than or Equal To Today Date validation annotation in MVC3

前端 未结 3 1606
北恋
北恋 2020-12-05 02:53

Has anyone seen an MVC3 data annotation for Date validation that requires a single selected date to be equal to or greater than current date?

If there\'s already a t

相关标签:
3条回答
  • 2020-12-05 03:18

    Create a custom attribute.

    public class CheckDateRangeAttribute: ValidationAttribute {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
            DateTime dt = (DateTime)value;
            if (dt >= DateTime.UtcNow) {
                return ValidationResult.Success;
            }
    
            return new ValidationResult(ErrorMessage ?? "Make sure your date is >= than today");
        }
    
    }
    

    code was written off the cuff so fix any errors :)

    0 讨论(0)
  • 2020-12-05 03:27

    Use [Remote] for special validations, simple and easy:

    Your model:

    [Remote("ValidateDateEqualOrGreater", HttpMethod="Post", 
        ErrorMessage = "Date isn't equal or greater than current date.")]
    public DateTime Date { get; set; }
    //other properties
    

    Your action:

    [HttpPost]
    public ActionResult ValidateDateEqualOrGreater(DateTime Date)
    {
         // validate your date here and return True if validated
         if(Date >= DateTime.Now)
         {
           return Json(true);
         }
         return Json(false);    
    }
    
    0 讨论(0)
  • 2020-12-05 03:43

    Simple way to accomplish this task is using CompareValidator.

    The code below uses AjaxControlToolKit's CalendarExtender. Copy the below code to your HTML directive

    <asp:TextBox ID="txtCompletionDate" runat="server" CssClass="txtNormal"></asp:TextBox>
                            <cc1:CalendarExtender ID="CalendarExtender1" TargetControlID="txtCompletionDate"
                                Format="dd/MM/yyyy" runat="server">
                            </cc1:CalendarExtender>
                            <asp:RequiredFieldValidator ID="rfvCompletionDate" runat="server" ControlToValidate="txtCompletionDate"
                                CssClass="labelError" ErrorMessage="*"></asp:RequiredFieldValidator>
                            <asp:CompareValidator ID="cvDate" runat="server" ControlToCompare="hiddenbox" ErrorMessage="*"
                                ControlToValidate="txtCompletionDate" CssClass="labelError" ToolTip="Completion  Date should be greater than or equal to Today"
                                Operator="GreaterThanEqual" Type="Date"></asp:CompareValidator>                        
                            <asp:TextBox ID="hiddenbox" runat="server" CssClass="hiddenbox">
    </asp:TextBox>
    

    add the below line in the CSS

    .hiddenbox {display:none;}
    
    0 讨论(0)
提交回复
热议问题