Reputation: 21
I am new to angular and I am not sure how to work with dates. I have a form
with name
and date of birth
.
Before submission I want to check if the person is older than 18 and show an error message before the form is submitted.
But I donot have access to the dob
variable in the form
unless it is submitted. In my code I have access to $scope.contact.dob
only inside addContact()
,( after the date is submitted). How do I do date of birth validations before form submission?
My code snippet is shown below
<form>
<input ng-model="contact.name">
<input ng-model="contact.dob" ng-min="minAge()">
<p ng-show="userForm.birthday.$error.min">Mustatleast 18.</p>
<button ng-click=addContact()></button>
</form>
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;
};
})
Upvotes: 1
Views: 2017
Reputation: 26444
In angular, while there is a directive for ng-minlength
, there is no built-in-directive ng-min
. Take a look at the documentation here.
https://docs.angularjs.org/api/ng/input/input%5Bnumber%5D
Instead of ng-min, use the HTML min
attribute.
Your code should look like this
<input ng-model="contact.dob" min="{{minAge()}}">
As for the error messages, you should take a look at ng-messages
.
Upvotes: 1