在输入类型日期的angularjs日期格式验证 [英] angularjs date format validation on input type date

查看:914
本文介绍了在输入类型日期的angularjs日期格式验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用AngularJS创建日期,并根据文档

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


带有日期验证和转换的输入。在不支持
但不支持HTML5日期输入的浏览器中,将使用一个文本元素。在
的情况下,文本必须以有效的ISO-8601日期格式
(yyyy-MM-dd)输入,例如:2009-01-06。由于许多现代浏览器
尚未支持此输入类型,因此通过占位符或标签在预期输入格式上向
用户提供提示很重要。

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.

它只接受有效的ISO-8601日期格式(yyyy-MM-dd)。

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>

但不行。

所以如何将默认日期格式更改为 dd / MM / yyyy 。这是 jsfiddle

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

推荐答案

我认为你应该写一个 ad hoc 指令,以便真正的跨浏览器兼容...

这样的一个:

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

这篇关于在输入类型日期的angularjs日期格式验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆