Verifying StartDate and EndDate using AngularJS and Bootstrap Datepicker

My HTML Coding

 <form name="myForm">
         <div class="row">
          <div class="col-md-2">
            <input data-ng-model="Data.StartDate" type="text" id="startDate"   name="startDate"
            class="form-control" data-datepicker-popup="MM-dd-yyyy" data-datepicker-append-to-body="true"
            data-is-open="popup.fromOpened" data-ng-click="fromOpen()" placeholder="Start Date" data-ng-required="true" />
        </div>
        <div class="col-md-2">
          <input data-ng-model="Data.EndDate" type="text" id="endDate" name="endDate"
            class="form-control" data-datepicker-popup="MM-dd-yyyy" data-datepicker-append-to-body="true"
            data-is-open="popup.toOpened" data-ng-click="toOpen()" placeholder="End Date" data-ng-required="true" />
        </div>
        <div class="col-md-2">
          <button data-ng-click="Search()" class="btn btn-info">Search</button>
        </div>
      </div>
      <div class="row">
        <span>Error list</span>
      </div>
    </form>

The Angular script provided is as follows.

 $scope.$watch('Data.StartDate', validateDates);
$scope.$watch('Data.EndDate', validateDates);

function validateDates() {
//      Some code to be written here for date validation
}

I am seeking assistance in implementing proper date validation on my webpage. Any guidance would be greatly appreciated. Thank you in advance

Answer №1

Simply include type="date" in the HTML input element.

Answer №2

Using `$watch` for example code can lead to a controller with over 500 lines, making it difficult to support and maintain when adding new fields.

Instead, I recommend the following approach:

  1. Create a ValidationFactory that houses validation methods for all field types;
  2. Define a FIELDS_CONFIG Object to store field configurations including name, error message, type, validation function, and value path in another factory;
  3. Develop a directive that performs validation only on specific elements like forms or divs, and watches the entire model provided to it;
  4. Organize all properties within a dedicated form model object.

With this setup, whenever a change occurs in the model, the directive will trigger a validation method from the ValidationFactory based on the field type using the specified value. The validation results will be stored in ValidationFactory.errors = {} with field names as keys for easy access to display any validation errors.

An alternative, albeit simpler but slightly against best practices, is to use the ng-change directive on each field needing validation. This directive would call

ValidationFactory.validateData(value, message)
, and any errors would be stored in ValidationFactory.errors = []. This allows for checking of errors using ValidationFactory.isAnyErrors() from parent controllers, among other places.

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

Issue arises when combining inline-block and overflow-wrap for div elements

I am facing an issue with two divs that look good on the same line when utilizing display: inline-block. However, if one of the containers contains an excessively long word that I attempt to wrap using overflow-wrap and word-break, it causes the container ...

Transform ISO-8859-1 encoding into UTF-8

Recently, I encountered an issue while sending a HTTP request using jQuery's ajax. The server, unfortunately, returns the response in ISO-8859-1 format while my page is set to UTF-8. This discrepancy causes some characters to become unreadable. How ...

Execute the getJSON calls in a loop for a count exceeding 100, and trigger another function once all

In order to process a large grid of data, I need to read it and then make a call to a $getJSON URL. This grid can contain over 100 lines of data. The $getJSON function returns a list of values separated by commas, which I add to an array. After the loop fi ...

Tips for horizontally aligning an item in a flexbox only when it wraps onto a new line

In my layout, I have a container that consists of text on the left and a button on the right. The challenge I'm facing is ensuring proper alignment when they are on the same line versus when the button wraps to a new line on smaller screens. Ideally, ...

Executing a function in Angular 2 depending on the class assigned to a <div>

In my HTML code, I am using *ngFor to iterate through an array of messages. <div *ngFor="let message of messages; let i=index" [focused]="i === activeIndex;" [ngClass]="{'message-list-active': activeIndex === i }" (click)="onAddtoMessag ...

Regular expressions are used for validation purposes

I've been using the regular expression shown below to validate certain text: ^\d+(?:fs|sf)[-+]\d+[hmd]$/ Here are some sample texts I have validated with this regular expression: 20fs-4d 10sf+20m 3fs-2h So far, it's been working we ...

Issue with React component not updating content after state changes in Next.js framework

Currently, I am facing an issue with my Header component not updating its content on state change. The goal is to show the user's Profile once the state changes, but unfortunately, it does not update immediately; it only changes after a page refresh o ...

The picture is not visible outside the parent container - why is it hidden?

Currently, I am working on project cards and using materialize css's image card to style them. One of the features that I particularly like is how it resizes the picture when included inside a container. This allows me to set a fixed height without wo ...

Error: Trying to destructure a non-iterable object with useContext in React is not valid

ERROR [TypeError: Invalid attempt to destructure non-iterable instance. In order to be iterable, non-array objects must have a Symbol.iterator method.] Using UserContext : import React, { useContext, useEffect, useLayoutEffect, useState } from "reac ...

Selecting the first li element using JQuery selectors

Can anyone help me with creating an onclick event that triggers when the user clicks on the first list item which is labeled as "Any Date"? I am looking to use jQuery to target this specific element. <ul id="ui-id-1" class="ui-menu ui-widget ui-widge ...

Show a Pop-Up When a Key is Pressed

My website popup features a 'Close' button in the top right corner, a text section with a background image, and a 'Print' button at the bottom. The popup automatically appears when the page loads. However, once closed, there is currentl ...

Using jQuery and PHP to send a dynamic form through AJAX

I'm currently working on a pet registration form where users can add new pets. When a user clicks the "add pet" button, I use jQuery to clone the pet section of the form and give each cloned section an id like #pet-2, #pet-3, and so on. Although my ...

The parent component is failing to pass the form values to the child form group in CVA

My Angular application (view source code on Stackblitz) is running Angular 15, and it utilizes reactive forms along with a ControlValueAccessor pattern to construct a parent form containing child form groups. However, I am encountering an issue where the d ...

What is causing the consistent occurrences of receiving false in Angular?

findUser(id:number):boolean{ var bool :boolean =false this.companyService.query().subscribe((result)=>{ for (let i = 0; i < result.json.length; i++) { try { if( id == result.json[i].user.id) ...

What is the best way to retrieve information from an Array within a JSON Object?

I currently have a Json object called FriendJson, which contains an array field named friends. This is the Json Object: [ { "id": 4, "updated": "2023-01-07T22:06:23.929206Z", "created": "2023-01-0 ...

The issue with fancybox links not functioning properly within ajax content

I'm looking to constantly update a specific section on my website using ajax, jquery, and php. Upon the initial page load, a javascript function is triggered to display the content of that section. Subsequently, json is utilized to check for any new ...

Ways to showcase numerous products within a single category label

views.py : def get_meals(request): template = loader.get_template('café/meals.html') meal_data = MealInfo.objects.all() category_data = MealsCategory.objects.all() context = { 'meals': meal_data, ' ...

Problems connecting to Azure SQL due to network interface issues, error code 26

My web application was successfully published on Azure, but I encountered an issue with SQL Network Interfaces, specifically error 26 - Error Locating Server/Instance Specified. Oddly enough, the application works perfectly fine when published on a differe ...

Executing a Python script asynchronously from a Node.js environment

I am currently managing a node.js program that handles approximately 50 different python script instances. My goal is to implement a throttling mechanism where only 4 processes can run in parallel at any given time. Initially, I attempted to create a simp ...

Is it permissible to use Aloha editor GPL v.2 on a business website?

While researching the licensing of Aloha Editor, I came across some confusing information. I found a reference to another editor under LGPL: However, I couldn't find a clear answer on whether I can use Aloha JS code on a commercial website with GPL v ...