Creating a bespoke validation in AngularJS to verify if the selected date falls within a specific range of weekdays

Hey there! I'm looking to enhance the validation process for a date input field in a unique manner.

Currently, my default validation setup looks like this:

<div>
  <input type="text" name="firstName" ng-model="appointmentForm.firstName" ng-minlength=2 required>
</div>
<div role="alert">
  <span class="error" ng-if="submitted && form.firstName.$error.minlength" >
    Please enter a valid first name
  </span>
</div>
...

Now, I want to implement a validator that checks if the selected date falls between Tuesday and Sunday. Here's an example of what I'm aiming for:

<input type="date" name="date" ng-model="appointmentForm.date" validate-weekday>

Could someone guide me on how to set up this custom validator on the Angular side?

Answer №1

Embarking on the right path means starting with a directive that adds a validation handler to the validator collection using your own logic.

To help you get started, I've provided some sample code that you can use as a template. Remember to customize the validation code to fit your specific business requirements.

app.directive('validateWeekday', [function () {

    function validate(value) {
        //replace me with correct logic
        return value == 'this is valid';
    }

    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, ele, attrs, ngModel) {
            ngModel.$validators.invalidWeekday = function (modelValue) {
                return validate(modelValue);
            }
        }
    }
}]);

Here's an example of how you might use this in your HTML:

<form name="appointmentForm">
    <input type="text" name="dateOfPurchase" ng-model="dateOfPurchase" validate-weekday>
    <div class="error-message" ng-show="appointmentForm.dateOfPurchase.$error.invalidWeekday">Valid date is required.</div>
</form>

Don't forget to explore ngMessages and other validation features in Angular 1.3 for a more refined and elegant code structure.

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

When should you use isRequired for PropType versus defaultProps in a React application?

I often find myself confused about when to use .isRequired versus .defaultProps={...}. I personally feel that I should avoid using isRequired, as it seems like creating a potential bug in the application. By using isRequired, it automatically removes the n ...

"Implementing the Format Function in AngularJS: A Step-by-Step Guide

I am currently working with AngularJS and have a scenario where I am making an $http Get call that returns some data. One of the fields is a boolean named PassFail, which currently displays as "true" or "false". However, I would like it to show as "Pass" o ...

Comparing jQuery's min-width and width properties: A guide on eliminating pixels

Exploring some basic jQuery and JavaScript here. When I use the .width() method, I get an integer value. However, when I use .css('min-width'), it returns a value in pixels which makes it challenging to perform calculations. What would be the be ...

Reducing size and Assembling JavaScript and CSS

I find myself in a bit of a dilemma when it comes to using just one JS file and one CSS file for a website. Let me elaborate: As someone who mainly works with CMS platforms like Joomla, I often run into issues during page speed tests where experts recomme ...

Adjust the viewing area dimensions on a web browser

Recently, while testing a web application page I developed with Selenium, I came across an interesting issue. After using the JavaScriptExecutor in Selenium to get the viewport size, I found that it was different for Chrome, IE, and Firefox. The sizes wer ...

AngularJS provides the ability to dynamically generate HTML attributes using the ng-repeat directive

Is it possible to dynamically add HTML attributes using ng-repeat? <select> <option ng-repeat="thing in things" {{thing.ghosted||'disabled'}}> {{thing.name}} </option> </select> Can someone help me figure ...

Utilizing Django to Showcase Images within DataTables and ListView

I am trying to incorporate a thumbnail image in a jQuery DataTables. A thread on Stack Overflow 1 suggests adding a js render function to the .DataTable settings. I want to implement this solution in a standard way, using Django's class-based ListVi ...

Unable to display socket data in Angular js Table using ng-repeat

div(ng-controller="dashController") nav.navbar.navbar-expand-sm.navbar-dark.fixed-top .container img(src='../images/Dashboard.png', alt='logo', width='180px') ul.navbar-nav li.nav-item ...

Encountered an issue while installing the "sharp" module on MAC M1

When I run npm run dev (gatsby develop) on my MacBook Pro M1 chip, it exits with the error message: Error: Something went wrong installing the "sharp" module However, when I run npm run dev on a MacBook Pro with an Intel chip, everything works fine. I&ap ...

Display options in Material-UI autocomplete only upon clicking the icon

Is there a way to display the options list only when clicking on the arrow icon as opposed to the textfield itself? I have reviewed the documentations without success in finding a solution. Example ...

Tips for utilizing maps in a react component within a Next.js application

I received an array of data from the backend that I need to display on a React component. home.js import Head from "next/head"; import Header from "../src/components/Header"; import * as React from 'react'; import { styled } ...

What is the method for an (angular) custom element to determine if a <slot> tag has been utilized?

I'm working with a custom element that has multiple named slots. Based on a certain state, one of the slots will be displayed. Here is an example of how the custom elements are structured: <slot></slot> <slot name="small"></slot& ...

Exploring the integration of data objects within a style tag in Vue.js

I'm currently experimenting with creating a parallax effect using background-position and a data object. <div class="parallaxBanner" :style="{scrollBanner}"> </div> <script> export default { data: function(){ ...

Ensure jQuery waits until the function has completed execution

Here is the script in question: var d; $(".circle").click(function() { var id = $(this).attr('id'); var MyDiv1 = document.getElementById(id); var name = MyDiv1.innerHTML; $.get("url", function(data){ d=data; }); d=d ...

Creating Stunning CSS Animations for a Slider Using SVG

Looking for help to create an SVG CSS animation for a slider using a mockup image. The animation will feature a balloon with a number value that zooms in and out from left to right or right to left. Currently stuck at the starting point and unsure how to ...

Is there a Rails 3 equivalent to $(document).ready() for ensuring that Highcharts loads correctly?

I am facing an issue with my highcharts chart not loading. I am looking for a way to delay the execution of the JavaScript file containing the chart data until after the partial has been passed into building the full page. Can someone provide guidance on ...

Error in React Native - Invalid component type provided

I'm encountering an issue while building a React Native app with Expo CLI. Every time I test it, I receive an error message. How can I troubleshoot and resolve this problem? Error: Element type is invalid: expected a string (for built-in components) ...

Retrieve the jQuery widget instance by selecting an element within the widget

I am currently developing a widget using the Jquery widget factory. The abbreviated version of the code looks something like this: _create: function(){ this.element.hide(); //hides original input element this.newInput=$("<input>"); //creates ...

Attempting to create a multi-page slider using a combination of CSS and JavaScript

Looking for help with creating a slider effect that is triggered when navigating to page 2. Ideally, the div should expand with a width of 200% or similar. Any assistance would be greatly appreciated! http://jsfiddle.net/juxzg6fn/ <html> <head& ...

When working with Angular1+ ES6 and using controller as a class, the utilization of Dependency Injections may be ambiguous within controller functions

I recently started using ES6 class for defining my controller, and here is the syntax I am using: export class SearchBarController { constructor($log) { 'ngInject'; $log.debug("Hello"); } textTyped($log){ $ ...