Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

c# - ASP MVC 5 Client Validation for Range of Datetimes

I want to check an Datetime field in a form. The field is valid between 01/10/2008 and 01/12/2008. Here is how I defined the viewmodel property:

    [Required(ErrorMessage = "The date value is mandatory")]
    [DataType(DataType.DateTime)]
    [Range(typeof(DateTime), "01/10/2008", "01/12/2008")]
    [DisplayName("When the work starts")]
    public DateTime StartWork { get; set; }

I want to validate this on the client side. But I get always an error. I give the value 01/11/2008 and it tells me, that the date must be defined between 01/10/2008 and 01/12/2008. I read that it doesn't work client validation without jquery, isn't it? Or I forgot anything? What alternatives are there to get any solution of that problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you can implement this using custom validation in MVC. Try using this:

[ValidateDateRange]
public DateTime StartWork { get; set; }

Here is your custom validation implementation:

namespace MVCApplication
    {   

        public class ValidateDateRange: ValidationAttribute
        {
            protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            {                 
               // your validation logic
                if (value >= Convert.ToDateTime("01/10/2008") && value <= Convert.ToDateTime("01/12/2008") )
                {
                    return ValidationResult.Success;
                }
                else
                {
                    return new ValidationResult("Date is not in given range.");
                }
            }
        }
    }

UPDATE:

You can also pass date ranges as parameters to make the validation a generic one:

[ValidateDateRange(FirstDate = Convert.ToDateTime("01/10/2008"), SecondDate = Convert.ToDateTime("01/12/2008"))]
public DateTime StartWork { get; set; }

Custom Validation:

    namespace MVCApplication
        {   

            public class ValidateDateRange: ValidationAttribute
            {
              public DateTime FirstDate { get; set; }
              public DateTime SecondDate { get; set; }

                protected override ValidationResult IsValid(object value, ValidationContext validationContext)
                {                 
                    // your validation logic
                    if (value >= FirstDate && value <= SecondDate)
                    {
                        return ValidationResult.Success;
                    }
                    else
                    {
                        return new ValidationResult("Date is not in given range.");
                    }
                }
            }
        }

UPDATE 2: (For Client Side) A very simple jQuery logic should do the client validation. Check below:

$(document).ready(function(){

  $("#btnSubmit").click(function(){

    var dt = $("#StartWork").val();

    var d = new Date(dt);
    var firstDate = new Date("2008-01-10");
    var secondDate = new Date("2008-01-12");

    if(d>= firstDate && d<= secondDate)
    {
      alert("Success");
    }
    else
    {
      alert("Date is not in given range.");
    }

  });

});

Please check this JSFiddle to see the working demo:Date Range Validation


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...