Having trouble implementing min and max date validation in Angular UI-Bootstrap datepicker with UI-Bootstrap version 1.3.3

My goal is to implement validation in my datepicker, preventing the user from selecting a date within 30 days before or after the current date. Here's the code snippet I'm currently using for the datepicker:

<div class="form-group" ng-class="{ 'has-error' : memberForm.dateOfBirth.$invalid && (memberForm.dateOfBirth.$touched || memberForm.$submitted) }">
  <label for="Date of Birth" class="" ng-hide="memberForm.dateOfBirth.$invalid && (memberForm.dateOfBirth.$touched || memberForm.$submitted)">Date of Birth(dd/mm/yyyy)*</label>
  <label class="error_message_text" ng-show="memberForm.dateOfBirth.$invalid && (memberForm.dateOfBirth.$touched || memberForm.$submitted)"> Date of birth is required </label>
  <p class="input-group" style="width:270px;">
    <input type="text" class="form-control" name="dateOfBirth" uib-datepicker-popup="dd/MM/yyyy" ng-model="dt" is-open="popup1.opened" datepicker-options="dateOptions" ng-required="true" close-text="Close" alt-input-formats="altInputFormats" />
    <span class="input-group-btn">
      <button type="button" class="btn btn-default" ng-click="open1()"><i class="glyphicon glyphicon-calendar"></i></button>
    </span>
  </p>
</div>

Additionally, these are the scripts I am utilizing -

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>  
<script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-1.3.3.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"> 

I have set up a Plunker demo here - https://plnkr.co/edit/RmDyhjKpEJvTMjNRp5LE?p=preview

If anyone has suggestions on how to implement this validation effectively, please share your insights!

Answer №1

There appears to be an issue with the code at this point:

$scope.minDate = date.setDate((new Date()).getDate() - 30);

Calling date.setDate(..) does not return the date object, so it should be corrected as follows:

$scope.toggleMin = function() {
    var date = new Date();
    date.setDate((new Date()).getDate() - 30);
    $scope.minDate = date;
  };
  $scope.toggleMin();


var date1 = new Date();
date1.setDate((new Date()).getDate() + 30);
$scope.dateOptions.maxDate = date1;

A minor correction has been made (added .dateOptions while assigning min date and max date).

 $scope.toggleMin = function() {
        var date = new Date();
        date.setDate((new Date()).getDate() - 30);
        $scope.minDate = date;
      };
      $scope.toggleMin();

    //  Add this for maxDate, no code was there in plunker
    var date1 = new Date();
    date1.setDate((new Date()).getDate() + 30);
    $scope.dateOptions.maxDate = date1;

For more information, please refer to the Plunker example provided below:

Answer Plunker- https://plnkr.co/edit/RmDyhjKpEJvTMjNRp5LE?p=preview

Answer №2

Utilize this method for verifying data

let currentDate = new Date()
let pastDate = new Date().setDate(currentDate.getDate()-30)

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

Incorporating onPause and onResume functionalities into a YouTube video featured on a page built with Ionic 2

I'm encountering a minor problem with a simple demo Android app built in Ionic 2. Whenever a Youtube video is playing on the Homepage, if the power button is pressed or the phone goes into sleep/lock mode, the Youtube video continues to play. This is ...

Inform jQuery that the draggable element is in the process of being dragged dynamically

Currently, this issue is a vital component of an ongoing task. Once we can resolve this issue, it will lead to the completion of this and another inquiry. The original objective can be found here: drag marker outside map to html element You can view the ...

The next function is not defined error in the controller function

Everything was running smoothly until I suddenly encountered this error message: ReferenceError: next is not defined. I'm puzzled because I didn't make any changes to this function. const Users = require('../data/users.model') exports ...

CSS to target every second visible tr element using the :nth-child(2n)

My table has a unique appearance (shown below) thanks to the application of CSS nth-child(2n). tr:nth-child(2n) {background-color: #f0f3f5;} https://i.sstatic.net/1AnDi.png I made some elements hidden on the vID, ID, and MO_Sub tr. <tr style="displa ...

Running a child process in the browser using Node.js with the help of browserify

Utilizing browserify to enable node.js functionality in the browser, I am attempting to run a child process in my index.js file: var exec = require('child_process').exec; //Checking the installed node version var ls = exec('node -v', f ...

Utilizing Vue.js for enhanced user experience, implementing Bootstrap modal with Google Maps autocomplete

I recently set up a Bootstrap modal that includes an <input>. To enable Google autocomplete for it, I utilized the commonly known trick below: .pac-container { z-index: 10000 !important; } However, I have encountered difficulty in getting the a ...

The JavaScript string in question is: "accepted === accepted && 50 > 100". I need to determine whether this string is valid or not by returning a boolean answer

I am developing a dynamic condition builder that generates a JavaScript string such as, tpc_1 === accepted && tpc_6 > 100 After the replace function, the new string becomes, accepted === accepted && 50 > 100 Now my challenge is to va ...

The login page continues to show an error message for incorrect credentials unless the submit button is clicked

My current project involves a React component called "Signin.js". Within this component, there are login input fields as I am working on creating a login system using Node.js, Express.js, and MySQL. To achieve this, I have set up a post request that sends ...

I am having trouble adding multiple items on different occasions - is it something to do with JQUERY

I have been working on a dynamic website that loads Firebase values into a table. However, I encountered an issue where the data does not appear when going back to the orders page after visiting another page. After some testing, I found that placing a but ...

Storing JSON data from a Github Gist in an array using the AJAX method - a step-by-step guide

I'm experimenting with storing JSON data in a variable and then randomly accessing it. (Superhero Alias Generator) The JSON data can be found on GitHub gist below I decided to try using the ajax method for the first time, but it doesn't seem to ...

Angular2 - Utilizing Promises within a conditional block

I'm currently facing an issue where I need to await a response from my server in order to determine if an email is already taken or not. However, I am struggling to achieve this synchronously. TypeScript is indicating that the function isCorrectEmail( ...

Transitioning the Background Image is a common design technique

After spending hours trying to figure out how to make my background "jumbotron" change images smoothly with a transition, I am still stuck. I have tried both internal scripts and JavaScript, but nothing seems to work. Is there any way to achieve this witho ...

Retrieving data from a remote source repeatedly based on user selections on a single page

In my current project, I am utilizing next js to build a web application. One of the pages in this app has the following structure: <page> <component_1> This component fetches data from a remote server using `getInitialProps` (alternat ...

Getting an HTML element by its ID that was passed from the ng-init directive in Angular can be achieved

When I use ng-click, I am able to retrieve the html element by id. However, when I use ng-init, I only get null. Please take a look at my codepen here. HTML Code: <script type="text/javascript"> var memId = "bb7de28f-0f89-4f14-8575-d494203acec7 ...

Unable to use 'ngFor' as it is not recognized as a property of ... in a mixed AngularJS and Angular environment

My AngularJS and Angular hybrid application is giving me trouble when I try to downgrade my Angular test.component. Every time I attempt it, I encounter the following error messages: Can't bind to 'ngFor' since it isn't a known pro ...

HTML: Base64 image not displaying properly due to incorrect height specification

I have a straightforward base64 image that I am having trouble with. The issue is that only the upper half of the image is displaying. If I try to adjust the height using the "style" attribute in the img tag: style="height: 300px;" it shows correctly. Ho ...

The defaultLocale setting in Next.js i18n is failing to retain the default language

I am currently working on setting my default language in Next.js i18n, but I keep encountering a problem where "En" is always set as the default language, acting as a fallback. Additionally, I am receiving this error message: Error: [@formatjs/intl Erro ...

What is causing the local storage to not persist after refreshing the page?

Even after a browser refresh, the button text 'completed' should remain intact depending on whether the variable item is true (after the button click). I have experimented with Chrome and believe the issue is not related to the browser. <temp ...

Resolve the route expression before the API request is fully processed

As a hobby coder, I have some gaps in my knowledge and despite trying various solutions, I have not been able to solve this issue. Idea Outcome My goal is to call my Express server, retrieve data from an external API, and render the data once it's f ...

Pagination in AngularJS that allows users to easily "jump to page"

Looking to enhance my pagination function by adding a textbox and button for users to input the desired page number. Any ideas or reference links on how to go about this? Thanks in advance! Here's my current HTML: <div class="pagingDiv"> <b ...