satya
satya

Reputation: 13

Date validation using angular js

I have start date and end date picker in format of mm-dd-yyyy.End date should be with in 10 days range of start date and end date should not be before start date. How to validate using angular js.Any help is greatly appreciated

Upvotes: 0

Views: 478

Answers (3)

arbghl
arbghl

Reputation: 368

Can you provide more details about this as in what library are you using for datepicker. It would help us answer.

Since you are using a datepicker you can restrict the date range in the fromDate field do not display any dates which are after a certain period (10 days from start date in you case).

jQuery datepicker allows this so does other datepickers.

EDIT: In your controller do something like this.

var newDate = new Date($scope.startdate.getFullYear(), $scope.startdate.getMonth(), $scope.startdate.getDate()+10);
$scope.dateOptions = {
 maxDate: newDate,
 dateFormat: 'dd/mm/YYYY'
};

And now you can pass dateOptions to your input.

Note: Post a minimal plunkr for faster resolution of your issues.

Upvotes: 0

JC Ford
JC Ford

Reputation: 7076

For simple pattern matching, you can use the ngPattern directive. For more complex validation (such as ensuring it's a valid date and within a certain range of another date), you will need to write your own validation directive or use the handy custom validation directive available from Angular-UI.

https://htmlpreview.github.io/?https://github.com/angular-ui/ui-validate/master/demo/index.html

Upvotes: 0

WilsonPena
WilsonPena

Reputation: 1571

I advise you to use moment.js. Here's a basic tutorial and help to get started: https://dzone.com/articles/getting-started-with-momentjs-intro-with-examples

Basically you would do:

function testDate(startDate, endDate){
    var start =  moment(startDate, 'mm-dd-yyyy');
    var end = moment(endDate, 'mm-dd-yyyy');
    if(endDate.isBefore(start)){
       //start before end
    }
    if(startDate.add('days', 11).isAfter(endDate)){
       //end not within 10 days range
    }
    //success!
}

It would be something like that. Hope it helps!

Upvotes: 1

Related Questions