Checking for date overlap between two textboxes in MVC5 when searching against a date field

Currently, I am exploring options to implement search filters for my model results. I have a field called RunDate and I intend to allow users to search between two dates using two textboxes.

@Html.TextBox("StartDate", null, new { @class = "datefield form-control", type = "date" })
@Html.TextBox("EndDate", null, new { @class = "datefield form-control", type = "date" })

<input type="submit" class="btn btn-primary" value="Search" />

This is what my controller index task looks like:

 public async Task<ActionResult> Index(int? jobId, int? page, DateTime? StartDate, DateTime? EndDate)
......
......
 if (StartDate.HasValue )
        {
            jobs = jobs.Where(s => s.RunAfter >= StartDate);
            pageNumber = 1;
        }
        if (EndDate.HasValue)
        {
            jobs = jobs.Where(s => s.RunAfter <= EndDate);
            pageNumber = 1;
        }

I want to prevent the search from executing if the dates overlap incorrectly, such as when StartDate > EndDate.

What would be the most effective way to achieve this? Do I need to use JavaScript and include a validate() function when clicking on the input?

I've explored Request Validation, but it's now considered Obsolete.

Another option could be to add a validationResult like this:

 if (StartDate > EndDate)
        {
            return new ValidationResult("EndDate must be greater than StartDate");
        }

However, I'm unsure about where to integrate this. So, what would be the most efficient approach to validating these form fields?

Answer №1

By encapsulating your form fields in a ViewModel, you can have this model implement the interface IValidatableObject.

public class SearchViewModel : IValidatableObject {
    public DateTime? StartDate { get; set; }
    public DateTime? EndDate { get; set; }
    // other properties ...

     // This method will be automatically called to check ModelState.IsValid
     public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
         if (StartDate > EndDate) {
             yield return new ValidationResult("EndDate must be greater than StartDate", "EndDate");
         }
         // Additional checks can be added here with more ValidationResult instances ...
     }
}

To validate ModelState in your Action method:

public async Task<ActionResult> Index(SearchViewModel postData) {
    if (!ModelState.IsValid) {
        // Handle errors, for example, return the Index View again (with errors already added)
    }
    // If there are no errors, proceed with the execution flow
}

You can display a list of errors in Razor using the following snippet:

 @Html.ValidationSummary()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Isn't AJAX all about the same origin policy?

Despite my confusion surrounding the same domain origin policy and jQuery AJAX, I have noticed that when I make a GET request to a URL using jQuery, I am able to successfully retrieve the results. This goes against what I understood about the restriction ...

Dynamic pop-up content based on AJAX response

I don't have much experience in web development, so please excuse any beginner mistakes;) Currently, I'm working on creating a dynamic popup window in HTML, which is hidden by CSS. When a button is clicked, an AJAX post request is triggered to r ...

Undefined Variables in AngularJS Directive Scopes

Check out this JSFiddle I created https://jsfiddle.net/9Ltyru6a/3/ I set up a controller and a directive in the fiddle to trigger a callback when a value is changed. Instead of using the ng-change directive in Angular, I wanted to create an event similar ...

Each block in Svelte includes a unique shorthand attribute

I have a JSON variable that holds attributes in a specific structure: // This json variable defines the attributes for elements to be created let myElements = [ { attr1: "myAttr1", attr2: "myAttr2", }, { ...

Creating atomic controller actions in Sails.js: A guide to optimizing your controller functions

If I am looking to perform multiple operations within a Sails.js controller, how can I ensure that these actions are atomic to maintain the correctness of the results? This includes not only database operations but also various Javascript processing tasks. ...

Email Activation Required for Registration

CREATE TABLE Member ( memberID int IDENTITY (2480,39) PRIMARY KEY, memberName nvarchar(70) NOT NULL, password nvarchar(30) NOT NULL, eMail nvarchar(100) NOT NULL, notify bit NOT NULL, isActive bit NOT NULL, ...

Submitting an HTML form with no input data

Looking to dynamically pass arguments between pages using the code below: <script type="text/javascript> function buildAndSubmitForm(index){ <? $args = 't='.$team.'&s='.$season.'&l='.$league.&apo ...

What sets Babel and TypeScript apart from each other in terms of functionality and features?

While TypeScript was utilized to create Angular2, Babel also appears quite similar. Many established companies prefer Babel over TypeScript. Here are some questions to consider: What specific advantages does each one offer? Which is a better or worse ch ...

Synchronous execution in Node.js: Best practices for coordinating tasks

While Node.js is known for its asynchronous nature, I am seeking to perform tasks in a sequential manner as outlined below: 1. Make an API request > 2. Convert the body from XML to JSON.stringify format > 3. Pass the string to a template. request.g ...

Ways to identify if the requested image is error-free (403 Forbidden)

One of my scripts loads an image from a specific source every 300 ms, but sometimes it receives a 403 Forbidden response. When this happens, the image element ends up blank. I want to find a way to verify if the image has received a valid 200 response befo ...

Exploring techniques for creating realistic dimensions in CSS

My goal is to create a responsive website that accurately displays an object with specified dimensions, such as a width of 100mm, regardless of the user's screen resolution. However, I am facing challenges in achieving this consistency across all devi ...

Differences in SVG rendering between Chrome and Firefox

I am eager to create a diagram on my website using SVG. To ensure the diagram is displayed in full screen, I am utilizing availHeight and availWidth to determine the client screen's height and width, then adjust the scaling accordingly. My current sc ...

Disabling a specific dropdown within ng-repeat in AngularJS

I've encountered a problem with the ng-repeat in my HTML code: <div ng-repeat="a in items"> <div> <span>{{a.name}}</span> </div> <div> <select ng-model="a.c_id" ng-options="d.c_id as d.description ...

(Jenkins) MsBuild Issue - Required Reference Not Found

In my C# development using .Net framework 4.6.1, all projects also target version 4.6.1. However, I encountered an error while building our Mvc application with MSbuild (Jenkins). The error is as follows: C:\Program Files (x86)\Jenkins\work ...

Using object syntax in React state management

I've been working on dynamically updating the state in my React app, and this is what the current state looks like: this.state = { title: "", image: "", imageFile: "", formTitle: "", formMessage: "", formImage: "", ...

I'm looking for a button that, when clicked, will first verify the password. If the password is "abcd," it will display another submit button. If not, it

<form action="#" method="post" target="_blank"> <div id = "another sub"> </br> <input type = "password" size = "25px" id="pswd"> </br> </div> <button><a href="tabl ...

Leverage shared techniques and libraries across two different projects

I have a NodeJS project set up on Firebase cloud functions, with our backend service (ExpressJS) as an HTTP function and some cron functions. The project structure looks like this: /project (the main directory for all cloud functions) - package.json ...

Enhance the functionality of Javascript Promise.then by allowing the argument function to accept an extra parameter

In my code, I am currently utilizing ES6 Promise as shown below: const ctx = {} Promise.resolve() .then(() => doSomethingWith(ctx)) .then((retValue) => doSomethingElseWith(retValue, ctx)) I wish to achieve something like this: const ctx = {} u ...

Formatting specific elements within an array

I am working with an array of names, some of which are repeated. These names are then split in half and displayed as li. One thing I am struggling to figure out is how to style the name Joeyc with text-decoration: line-through; on all instances of .book w ...

How to remove a variable definition in Typescript

Is there a way to reset a variable to undefined after assigning it a value? To check, I am using the Underscore function _.isUndefined(). I have attempted both myVariable = undefined and delete myVariable without success. ...