Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs date format validation on input type date

I'm trying to create date using AngularJS and as per the documentation

Input with date validation and transformation. In browsers that do not yet support the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601 date format (yyyy-MM-dd), for example: 2009-01-06. Since many modern browsers do not yet support this input type, it is important to provide cues to users on the expected input format via a placeholder or label.

it only accepts valid ISO-8601 date format (yyyy-MM-dd).

I've tried to define the new date format in the pattern's attribute as shown in the following code:

<div ng-app="">
  <form name="frmSPA" novalidate>
    <input type="date" placeholder="Enter SPA Date" pattern="dd/MM/yyyy" name="SPADate" ng-model="SPADate" ng-required="true" />
    <span ng-show="frmSPA.SPADate.$touched && frmSPA.SPADate.$error.required">SPA Date is required</span>
    <span ng-show="frmSPA.SPADate.$touched && frmSPA.SPADate.$error.date">Not a valid date</span>
  </form>
</div>

but it doesn't work.

So how to change the default date format into dd/MM/yyyy. Here is the jsfiddle.

like image 744
Willy Avatar asked May 31 '26 19:05

Willy


1 Answers

I think you should write an ad hoc directive, to be really cross-browser compatible...
Something like this:

angular
    .module('MyApp', [])
    .controller('MainCtrl', function ($scope, dateFilter) {
        $scope.date = new Date();
    })
    .directive(
        'dateInput',
        function(dateFilter) {
            return {
                require: 'ngModel',
                template: '<input type="date"></input>',
                replace: true,
                link: function(scope, elm, attrs, ngModelCtrl) {
                    ngModelCtrl.$formatters.unshift(function (modelValue) {
                        return dateFilter(modelValue, 'dd-MM-yyyy');
                    });

                    ngModelCtrl.$parsers.unshift(function(viewValue) {
                        return new Date(viewValue);
                    });
                },
            };
    });

jsfiddle

like image 161
MarcoS Avatar answered Jun 02 '26 07:06

MarcoS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!