Angular Date of Birth Verification

I'm new to Angular and struggling with date handling. I have a form that includes fields for the user's name and their date of birth.

Before submitting the form, I need to validate that the person is over 18 years old and display an error message if they are not. However, I can't access the dob variable in the form until it is submitted. The only place I have access to $scope.contact.dob is inside the addContact() function after the submission. How can I validate the date of birth before form submission?

Here's a snippet of my code:

<form>
    <input ng-model="contact.name">
    <input ng-model="contact.dob" ng-min="minAge()">
    <p  ng-show="userForm.birthday.$error.min">Must be at least 18.</p>
    <button ng-click=addContact()></button>
</form>

Here's my controller:

.controller("myctrl", function($scope){
    $scope.addContact = fucntion(){
        console.log($scope.contact)
        $scope.contact.dob
    }
    $scope.minAge = function () {
        var current = new Date();
        var minYear = current.getFullYear() - 100;
        var min = new Date(minYear,current.getMonth(),current.getDate()).toISOString();
        return min;
    };

})

Answer №1

In angular, there's a directive called ng-minlength, but oddly enough, there isn't one for ng-min. Make sure to check out the documentation provided.

https://docs.angularjs.org/api/ng/input/input%5Bnumber%5D

If you need something similar to ng-min, you can simply use the HTML min attribute instead.

Your implementation will resemble this:

<input ng-model="contact.dob" min="{{minAge()}}">

To handle error messages effectively, consider utilizing ng-messages.

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

Need help setting parsed values on jQuery Autocomplete after Keyup event?

I am using the Bing API to retrieve values by accessing this link: When I parse and append the results on keyup, it works fine. However, when I try to set the results on jQuery's autocomplete, it does not display properly. For example, you can view ...

Tips for retrieving JSON data using ajax with jPut

Recently, I stumbled upon a handy jQuery plugin called Jput that allows for easy appending of JSON data to HTML content. You can check it out here. However, I am curious about the process of sending and retrieving JSON data via AJAX. Any insights or guida ...

Guide to verifying a value within a JSON object in Ionic 2

Is there a way to check the value of "no_cover" in thumbnail[0] and replace it with asset/sss.jpg in order to display on the listpage? I have attempted to include <img src="{{item.LINKS.thumbnail[0]}}"> in Listpage.html, but it only shows the thumbna ...

Employing asynchronous operations and the power of async/await for achieving seamless integration

I am currently facing an issue where I need to retrieve queries from a database stored in Postgres. A function is utilized, which employs a callback mechanism. In order to fetch rows from the database, there exists a function called getRecipesByCategoryFo ...

Exploring the capabilities of the jQuery `val()` function alongside the dynamic framework

Whenever I have a JavaScript variable that contains HTML printed from a table on my server, I encounter issues when using it in a jQuery function like val(). The problem arises every time someone enters content with special characters like " or '. Thi ...

Next.js encountered an issue when trying to read properties of null, specifically the 'push' property, resulting in a TypeError

I am utilizing the sweetalert2 library for displaying popups: export default function Home() { const MySwal = withReactContent(Swal) useEffect(() => { MySwal.fire({ showConfirmButton: false, customClass: { ...

Changing a "boolean bit array" to a numerical value using Typescript

Asking for help with converting a "boolean bit array" to a number: const array: boolean[] = [false, true, false, true]; // 0101 Any ideas on how to achieve the number 5 from this? Appreciate any suggestions. Thanks! ...

Access the JavaScript variable in a webview and store it in an Android variable

I have been attempting to retrieve a variable from a webview, but I am only able to make modifications like this: browser.loadUrl("javascript:var x = document.getElementById('login').value = 'something';"); However, I need to be able ...

Angular and Bootstrap4: The Perfect Duo for Modals

I need to display a Bootstrap4 modal window in Angular when a specific condition is met in my "bookTour" method without the need for a direct button click. How can I achieve this? Below is the code snippet: html <div class="modal" id="myModal" [ngClass ...

Updating Page Content with JQuery AJAX Post Without Page Reload

So I realize I may be asking a question that has been asked before, but as a complete beginner with AJAX jQuery, I'm not sure what to search for. I've tried searching without success, so please bear with me. I have a PHP WordPress site that defa ...

Obtaining a return value from a function that involves a series of chained Ajax requests in jQuery

I'm facing an issue with my function that involves chained Ajax requests. Function A and B are both Ajax requests, where A runs first and B runs after A returns its data. The problem arises when Function C executes Function B. Upon execution of Funct ...

Angular 4 with Typescript allows for the quick and easy deletion of multiple selected rows

I am currently working on an application where I need to create a function that will delete the selected checkboxes from an array. I have managed to log the number of checkboxes that are selected, but I am struggling to retrieve the index numbers of these ...

Eradicate white space in a JavaScript code

Calling all JS programmers! Here's a challenge for you, check out this demo: https://codepen.io/gschier/pen/jkivt I'm looking to tweak 'The pen is simple.' to be 'The pen issimple.' by removing the extra space after 'is& ...

Retrieving an item within another item

I'm attempting to retrieve the value of usertype within the result object, but I'm encountering issues with this. Here's what I've tried so far: if(data.result.usertype === 2){ console.log("redirect to type 2 user") } else if(data.re ...

Arrange two divs with a full width of 100% next to each other

Is there a way to create two divs, each taking up 100% of the page width and side by side within a wrapper with overflow:hidden? How can I achieve this? I attempted using inline-block, but it didn't produce the desired outcome. Similarly, when I tri ...

Refreshing the page causes Firebase authentication to vanish

My React app integrates Firebase authentication. However, I am facing an issue where the firebase:authUser is stored in localStorage upon successful login, but gets cleared on every page refresh resulting in a lost session. Surprisingly, browsing through o ...

Utilizing React Views in an Express Environment

I am struggling to find a simple example that demonstrates how to connect an Express.js route to render a React view. This is what I have tried so far. +-- app.js +-- config | +-- server.js +-- routes | +-- index.js +-- views | +-- index.html app. ...

What is the best way to iterate through a JSON file?

Looking at my JSON file: { "stats": { "operators": { "recruit1": { "won": 100, "lost": 50, "timePlayed": 1000 }, "recruit2": { "won": 200, ...

Using Jquery to change an id with the .attr method may not always produce the desired results

I have a div element that functions as a button when clicked, with the ID of knight. Every time I click on any of the 3 buttons (including knight), it changes the ID of knight to elf (yes, I'm creating a game). I have a hover effect for knight usi ...

The Push Over Menu is malfunctioning and not functioning properly

I am facing an issue with pushing my menu along with the content to the right. The JS code I have is not working as expected. When I click on <div class="menu-btn toggle"></div>, the menu does not trigger. Can someone help me understand why thi ...