【问题标题】:how to show validation error when user enter invalid date format on button click?当用户在按钮单击时输入无效的日期格式时如何显示验证错误?
【发布时间】:2019-04-06 05:48:32
【问题描述】:

当用户输入无效的日期格式时,有什么方法可以显示验证错误消息或边框变为红色?。在我的演示应用程序中有两个输入字段,我在其中显示日期,如“16-jun-1989”。现在用户如果用户输入无效格式,则仅以这种格式(即有效)编辑此字段我想在按钮单击时显示错误消息或在按钮单击时边框变为红色 这是我的代码 http://plnkr.co/edit/xoTH3uJZSVx0W78rwhMt?p=preview

var app = angular.module('plunker', ['angularMoment']);

app.controller('MainCtrl', function($scope ,moment) {
  $scope.name = 'World';
  console.log(moment)
  var d = new Date(613938600000);
  $scope.c = {
   ab: {
      name:'abc'
    },
   date: {
      name: moment(d).format('DD-MMM-YYYY')
    }
    };

    $scope.onclick =function(){
        console.log($scope.c)
    }

});

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    由于您已经在使用时刻,请检查日期是否有效:

    moment($scope.c.date.name).isValid()
    

    一个工作示例here.

    【讨论】:

      【解决方案2】:

      虽然这已经有了答案。您可能还对确保准确指定日期感兴趣。接受的答案中的验证并不严格: 这应该可以解决这个问题:

      $scope.onclick = function() {
          if (!moment($scope.c.date.name, 'DD-MMM-YYYY').isValid()) {
            alert('Date must be in the format 02-Nov-2018');
          } else {
            alert('All good');
          }
      }
      

      moment 函数的第二个参数确保了这种严格性。

      【讨论】:

        猜你喜欢
        • 2011-02-17
        • 2013-06-02
        • 1970-01-01
        • 2021-01-27
        • 2019-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多