Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 865
MrScf Avatar asked Nov 28 '14 05:11

MrScf


People also ask

How do I make sure client validation is enabled in MVC?

We can enable and disable the client-side validation by setting the values of ClientValidationEnabled & UnobtrusiveJavaScriptEnabled keys true or false. This setting will be applied to application level. For client-side validation, the values of above both the keys must be true.

What is the use of ModelState in MVC?

The ModelState has two purposes: to store and submit POSTed name-value pairs, and to store the validation errors associated with each value.

What ModelState is IsValid validate?

Model validation occurs after model binding and reports errors where data doesn't conform to business rules. For example, a 0 is entered in a field that expects a rating between 1 and 5. Web API controllers don't have to check ModelState. IsValid if they have the [ApiController] attribute.


2 Answers

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

like image 74
Saket Kumar Avatar answered Sep 29 '22 04:09

Saket Kumar


Though portions of this have been posted before and downvoted as not working. I can confirm this does work as long as you have both the range and the format string specified.

[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:mm-dd-yyyy}", ApplyFormatInEditMode = true)]
[Range(typeof(DateTime), "1/1/1900", "12/31/2018",
    ErrorMessage = "Value for {0} must be between {1} and {2}")]
[Display(Name = "Date of Birth")]
public DateTime DateOfBirth { get; set; }
like image 42
Aleksander Brown Avatar answered Sep 29 '22 03:09

Aleksander Brown