2

When trying to define more than one input date format for Date Picker we seem to have an issue where only one format can be defined. If this format is not met it defaults to americanised date format (MM/dd/YYYY).

For example if we set the format to dd-MM-yyyy but enter the date as 7/8/09, this is interpreted as the 8th of July 2009.

Is there a way of accepting and validating more than one date format, such as:

'dd-MM-yyyy',
'dd.MM.yyyy',
'dd/MM/yyyy',
'dd-MM-yy',
'dd.MM.yy',
'dd/MM/yy,
'd/M/yy'

1 Answer 1

2

you can use parser to parse the value before it being attached to datepicker

csapp.directive("csDateConverter", function () {

var linkFunction = function (scope, element, attrs, ngModelCtrl) {

    ngModelCtrl.$parsers.push(function (datepickerValue) {
        //convert the date as per your specified format
        var date = moment(datepickerValue, scope.format) 

        //convert it to the format recognized by datepicker
        return date.format("YYYY-MM-DD");
    });
};

return {
    scope: {format: '='}
    restrict: "A",
    require: "ngModel",
    link: linkFunction
};
});

and you can use it like this

<datepicker ng-model="dt" cs-date-converter="yyyy.mm.dd"></datepicker>

EDIT as per comments

removed isolate scope & changed scope.format to attrs.format

csapp.directive("csDateConverter", function () {

var linkFunction = function (scope, element, attrs, ngModelCtrl) {

    ngModelCtrl.$parsers.push(function (datepickerValue) {
        //convert the date as per your specified format
        var date = moment(datepickerValue, attrs.format.toUpperCase()) 

        //convert it to the format recognized by datepicker
        return date.format("YYYY-MM-DD");
    });
};

return {
    restrict: "A",
    require: "ngModel",
    link: linkFunction
};
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your idea. The problem is though, that this throws Error: $compile:multidir Multiple Directive Resource Contention as both directives have an isolated scope.
easy one to fix.. remove isolate scope from this directive... check the edit
How would this be accomplished with a text input using datepicker-popup?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.